service.cc 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  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. #include "dinit-socket.h"
  18. /*
  19. * service.cc - Service management.
  20. * See service.h for details.
  21. */
  22. // from dinit.cc:
  23. void open_control_socket(bool report_ro_failure = true) noexcept;
  24. void setup_external_log() noexcept;
  25. extern EventLoop_t eventLoop;
  26. // Find the requested service by name
  27. static ServiceRecord * find_service(const std::list<ServiceRecord *> & records,
  28. const char *name) noexcept
  29. {
  30. using std::list;
  31. list<ServiceRecord *>::const_iterator i = records.begin();
  32. for ( ; i != records.end(); i++ ) {
  33. if (strcmp((*i)->getServiceName().c_str(), name) == 0) {
  34. return *i;
  35. }
  36. }
  37. return (ServiceRecord *)0;
  38. }
  39. ServiceRecord * ServiceSet::find_service(const std::string &name) noexcept
  40. {
  41. return ::find_service(records, name.c_str());
  42. }
  43. void ServiceSet::startService(const char *name)
  44. {
  45. using namespace std;
  46. ServiceRecord *record = loadServiceRecord(name);
  47. record->start();
  48. processQueues(true);
  49. }
  50. void ServiceSet::stopService(const std::string & name) noexcept
  51. {
  52. ServiceRecord *record = find_service(name);
  53. if (record != nullptr) {
  54. record->stop();
  55. processQueues(false);
  56. }
  57. }
  58. // Called when a service has actually stopped; dependents have stopped already, unless this stop
  59. // is due to an unexpected process termination.
  60. void ServiceRecord::stopped() noexcept
  61. {
  62. if (onstart_flags.runs_on_console) {
  63. tcsetpgrp(0, getpgrp());
  64. discard_console_log_buffer();
  65. releaseConsole();
  66. }
  67. force_stop = false;
  68. // If we are a soft dependency of another target, break the acquisition from that target now:
  69. bool will_restart = (desired_state == ServiceState::STARTED)
  70. && service_set->get_auto_restart();
  71. if (! will_restart) {
  72. for (auto dependency : soft_dpts) {
  73. if (dependency->holding_acq) {
  74. dependency->holding_acq = false;
  75. release();
  76. }
  77. }
  78. }
  79. for (auto dependency : depends_on) {
  80. // we signal dependencies in case they are waiting for us to stop - but only if we won't
  81. // restart or if they are stopping uninterruptibly.
  82. if (! will_restart || ! dependency->can_interrupt_stop()) {
  83. dependency->dependentStopped();
  84. }
  85. }
  86. service_state = ServiceState::STOPPED;
  87. if (will_restart) {
  88. // Desired state is "started".
  89. restarting = true;
  90. service_set->addToStartQueue(this);
  91. }
  92. else {
  93. if (socket_fd != -1) {
  94. close(socket_fd);
  95. socket_fd = -1;
  96. }
  97. if (start_explicit) {
  98. start_explicit = false;
  99. release();
  100. }
  101. else if (required_by == 0) {
  102. service_set->service_inactive(this);
  103. }
  104. }
  105. logServiceStopped(service_name);
  106. notifyListeners(ServiceEvent::STOPPED);
  107. }
  108. dasynq::rearm ServiceChildWatcher::status_change(EventLoop_t &loop, pid_t child, int status) noexcept
  109. {
  110. base_process_service *sr = service;
  111. sr->pid = -1;
  112. sr->exit_status = status;
  113. // Ok, for a process service, any process death which we didn't rig
  114. // ourselves is a bit... unexpected. Probably, the child died because
  115. // we asked it to (sr->service_state == STOPPING). But even if
  116. // we didn't, there's not much we can do.
  117. if (sr->waiting_for_execstat) {
  118. // We still don't have an exec() status from the forked child, wait for that
  119. // before doing any further processing.
  120. return rearm::REMOVE;
  121. }
  122. // Must deregister now since handle_exit_status might result in re-launch:
  123. deregister(loop, child);
  124. sr->handle_exit_status(status);
  125. return rearm::REMOVED;
  126. }
  127. bool ServiceRecord::do_auto_restart() noexcept
  128. {
  129. if (auto_restart) {
  130. return service_set->get_auto_restart();
  131. }
  132. return false;
  133. }
  134. void process_service::handle_exit_status(int exit_status) noexcept
  135. {
  136. bool did_exit = WIFEXITED(exit_status);
  137. bool was_signalled = WIFSIGNALED(exit_status);
  138. if (exit_status != 0 && service_state != ServiceState::STOPPING) {
  139. if (did_exit) {
  140. log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
  141. }
  142. else if (was_signalled) {
  143. log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
  144. }
  145. }
  146. if (service_state == ServiceState::STARTING) {
  147. if (did_exit && WEXITSTATUS(exit_status) == 0) {
  148. started();
  149. }
  150. else {
  151. failed_to_start();
  152. }
  153. }
  154. else if (service_state == ServiceState::STOPPING) {
  155. // We won't log a non-zero exit status or termination due to signal here -
  156. // we assume that the process died because we signalled it.
  157. stopped();
  158. }
  159. else if (smooth_recovery && service_state == ServiceState::STARTED && desired_state == ServiceState::STARTED) {
  160. // TODO if we are pinned-started then we should probably check
  161. // that dependencies have started before trying to re-start the
  162. // service process.
  163. restart_ps_process();
  164. return;
  165. }
  166. else {
  167. if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
  168. forceStop();
  169. }
  170. service_set->processQueues(false);
  171. }
  172. void bgproc_service::handle_exit_status(int exit_status) noexcept
  173. {
  174. bool did_exit = WIFEXITED(exit_status);
  175. bool was_signalled = WIFSIGNALED(exit_status);
  176. if (exit_status != 0 && service_state != ServiceState::STOPPING) {
  177. if (did_exit) {
  178. log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
  179. }
  180. else if (was_signalled) {
  181. log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
  182. }
  183. }
  184. if (doing_recovery) {
  185. // (BGPROCESS only)
  186. doing_recovery = false;
  187. bool need_stop = false;
  188. if ((did_exit && WEXITSTATUS(exit_status) != 0) || was_signalled) {
  189. need_stop = true;
  190. }
  191. else {
  192. // We need to re-read the PID, since it has now changed.
  193. if (pid_file.length() != 0) {
  194. if (! read_pid_file()) {
  195. need_stop = true;
  196. }
  197. }
  198. }
  199. if (need_stop) {
  200. // Failed startup: no auto-restart.
  201. desired_state = ServiceState::STOPPED;
  202. forceStop();
  203. service_set->processQueues(false);
  204. }
  205. return;
  206. }
  207. if (service_state == ServiceState::STARTING) {
  208. // POSIX requires that if the process exited clearly with a status code of 0,
  209. // the exit status value will be 0:
  210. if (exit_status == 0) {
  211. if (pid_file.length() != 0 && ! read_pid_file()) {
  212. failed_to_start();
  213. }
  214. else {
  215. started();
  216. }
  217. }
  218. else {
  219. failed_to_start();
  220. }
  221. }
  222. else if (service_state == ServiceState::STOPPING) {
  223. // We won't log a non-zero exit status or termination due to signal here -
  224. // we assume that the process died because we signalled it.
  225. stopped();
  226. }
  227. else if (smooth_recovery && service_state == ServiceState::STARTED && desired_state == ServiceState::STARTED) {
  228. // TODO if we are pinned-started then we should probably check
  229. // that dependencies have started before trying to re-start the
  230. // service process.
  231. doing_recovery = true;
  232. restart_ps_process();
  233. return;
  234. }
  235. else {
  236. if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
  237. forceStop();
  238. }
  239. service_set->processQueues(false);
  240. }
  241. void scripted_service::handle_exit_status(int exit_status) noexcept
  242. {
  243. bool did_exit = WIFEXITED(exit_status);
  244. bool was_signalled = WIFSIGNALED(exit_status);
  245. if (service_state == ServiceState::STOPPING) {
  246. if (did_exit && WEXITSTATUS(exit_status) == 0) {
  247. stopped();
  248. }
  249. else {
  250. // ??? failed to stop! Let's log it as info:
  251. if (did_exit) {
  252. log(LogLevel::INFO, "Service ", service_name, " stop command failed with exit code ", WEXITSTATUS(exit_status));
  253. }
  254. else if (was_signalled) {
  255. log(LogLevel::INFO, "Serivice ", service_name, " stop command terminated due to signal ", WTERMSIG(exit_status));
  256. }
  257. // Just assume that we stopped, so that any dependencies
  258. // can be stopped:
  259. stopped();
  260. }
  261. service_set->processQueues(false);
  262. }
  263. else { // STARTING
  264. if (exit_status == 0) {
  265. started();
  266. }
  267. else {
  268. // failed to start
  269. if (did_exit) {
  270. log(LogLevel::ERROR, "Service ", service_name, " command failed with exit code ", WEXITSTATUS(exit_status));
  271. }
  272. else if (was_signalled) {
  273. log(LogLevel::ERROR, "Service ", service_name, " command terminated due to signal ", WTERMSIG(exit_status));
  274. }
  275. failed_to_start();
  276. }
  277. service_set->processQueues(true);
  278. }
  279. }
  280. rearm ServiceIoWatcher::fd_event(EventLoop_t &loop, int fd, int flags) noexcept
  281. {
  282. base_process_service *sr = service;
  283. sr->waiting_for_execstat = false;
  284. int exec_status;
  285. int r = read(get_watched_fd(), &exec_status, sizeof(int));
  286. deregister(loop);
  287. close(get_watched_fd());
  288. if (r > 0) {
  289. // We read an errno code; exec() failed, and the service startup failed.
  290. sr->pid = -1;
  291. log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
  292. if (sr->service_state == ServiceState::STARTING) {
  293. sr->failed_to_start();
  294. }
  295. else if (sr->service_state == ServiceState::STOPPING) {
  296. // Must be a scripted service. We've logged the failure, but it's probably better
  297. // not to leave the service in STARTED state:
  298. sr->stopped();
  299. }
  300. }
  301. else {
  302. // exec() succeeded.
  303. if (sr->service_type == ServiceType::PROCESS) {
  304. // This could be a smooth recovery (state already STARTED). Even more, the process
  305. // might be stopped (and killed via a signal) during smooth recovery. We don't to
  306. // process startup again in either case, so we check for state STARTING:
  307. if (sr->service_state == ServiceState::STARTING) {
  308. sr->started();
  309. }
  310. }
  311. if (sr->pid == -1) {
  312. // Somehow the process managed to complete before we even saw the status.
  313. sr->handle_exit_status(sr->exit_status);
  314. }
  315. }
  316. sr->service_set->processQueues(true);
  317. return rearm::REMOVED;
  318. }
  319. void ServiceRecord::require() noexcept
  320. {
  321. if (required_by++ == 0) {
  322. if (! prop_require) {
  323. prop_require = true;
  324. prop_release = false;
  325. service_set->addToPropQueue(this);
  326. }
  327. if (service_state == ServiceState::STOPPED) {
  328. // (In any other state, the service is already considered active.)
  329. service_set->service_active(this);
  330. }
  331. }
  332. }
  333. void ServiceRecord::release() noexcept
  334. {
  335. if (--required_by == 0) {
  336. desired_state = ServiceState::STOPPED;
  337. // Can stop, and can release dependencies now:
  338. prop_release = true;
  339. prop_require = false;
  340. service_set->addToPropQueue(this);
  341. if (service_state != ServiceState::STOPPED) {
  342. service_set->addToStopQueue(this);
  343. }
  344. else {
  345. service_set->service_inactive(this);
  346. }
  347. }
  348. }
  349. void ServiceRecord::release_dependencies() noexcept
  350. {
  351. for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
  352. (*i)->release();
  353. }
  354. for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
  355. ServiceRecord * to = i->getTo();
  356. if (i->holding_acq) {
  357. to->release();
  358. i->holding_acq = false;
  359. }
  360. }
  361. }
  362. void ServiceRecord::start(bool activate) noexcept
  363. {
  364. if (activate && ! start_explicit) {
  365. require();
  366. start_explicit = true;
  367. }
  368. if (desired_state == ServiceState::STARTED && service_state != ServiceState::STOPPED) return;
  369. desired_state = ServiceState::STARTED;
  370. service_set->addToStartQueue(this);
  371. }
  372. void ServiceRecord::do_propagation() noexcept
  373. {
  374. if (prop_require) {
  375. // Need to require all our dependencies
  376. for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
  377. (*i)->require();
  378. }
  379. for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
  380. ServiceRecord * to = i->getTo();
  381. to->require();
  382. i->holding_acq = true;
  383. }
  384. prop_require = false;
  385. }
  386. if (prop_release) {
  387. release_dependencies();
  388. prop_release = false;
  389. }
  390. if (prop_failure) {
  391. prop_failure = false;
  392. failed_to_start(true);
  393. }
  394. if (waiting_for_deps) {
  395. if (service_state == ServiceState::STARTING) {
  396. if (startCheckDependencies(false)) {
  397. allDepsStarted();
  398. }
  399. }
  400. else if (service_state == ServiceState::STOPPING) {
  401. if (stopCheckDependents()) {
  402. all_deps_stopped();
  403. }
  404. }
  405. }
  406. }
  407. void ServiceRecord::execute_transition() noexcept
  408. {
  409. bool is_started = (service_state == ServiceState::STARTED)
  410. || (service_state == ServiceState::STARTING && can_interrupt_start());
  411. bool is_stopped = (service_state == ServiceState::STOPPED)
  412. || (service_state == ServiceState::STOPPING && can_interrupt_stop());
  413. if (is_started && (desired_state == ServiceState::STOPPED || force_stop)) {
  414. if (! pinned_started) {
  415. do_stop();
  416. }
  417. }
  418. else if (is_stopped && desired_state == ServiceState::STARTED) {
  419. if (! pinned_stopped) {
  420. do_start();
  421. }
  422. }
  423. }
  424. void ServiceRecord::do_start() noexcept
  425. {
  426. if (pinned_stopped) return;
  427. if (service_state != ServiceState::STOPPED) {
  428. // We're already starting/started, or we are stopping and need to wait for
  429. // that the complete.
  430. if (service_state != ServiceState::STOPPING || ! can_interrupt_stop()) {
  431. return;
  432. }
  433. // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
  434. // but if so they are waiting (for us), so they too can be instantly returned to
  435. // STARTING state.
  436. notifyListeners(ServiceEvent::STOPCANCELLED);
  437. }
  438. service_state = ServiceState::STARTING;
  439. waiting_for_deps = true;
  440. // Ask dependencies to start, mark them as being waited on.
  441. if (! startCheckDependencies(true)) {
  442. return;
  443. }
  444. // Actually start this service.
  445. allDepsStarted();
  446. }
  447. void ServiceRecord::dependencyStarted() noexcept
  448. {
  449. if (service_state == ServiceState::STARTING && waiting_for_deps) {
  450. service_set->addToPropQueue(this);
  451. }
  452. }
  453. bool ServiceRecord::startCheckDependencies(bool start_deps) noexcept
  454. {
  455. bool all_deps_started = true;
  456. for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
  457. if ((*i)->service_state != ServiceState::STARTED) {
  458. if (start_deps) {
  459. all_deps_started = false;
  460. (*i)->start(false);
  461. }
  462. else {
  463. return false;
  464. }
  465. }
  466. }
  467. for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
  468. ServiceRecord * to = i->getTo();
  469. if (start_deps) {
  470. if (to->service_state != ServiceState::STARTED) {
  471. to->start(false);
  472. i->waiting_on = true;
  473. all_deps_started = false;
  474. }
  475. else {
  476. i->waiting_on = false;
  477. }
  478. }
  479. else if (i->waiting_on) {
  480. if (to->service_state != ServiceState::STARTING) {
  481. // Service has either started or is no longer starting
  482. i->waiting_on = false;
  483. }
  484. else {
  485. // We are still waiting on this service
  486. return false;
  487. }
  488. }
  489. }
  490. return all_deps_started;
  491. }
  492. bool ServiceRecord::open_socket() noexcept
  493. {
  494. if (socket_path.empty() || socket_fd != -1) {
  495. // No socket, or already open
  496. return true;
  497. }
  498. const char * saddrname = socket_path.c_str();
  499. uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
  500. struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
  501. if (name == nullptr) {
  502. log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
  503. return false;
  504. }
  505. // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
  506. unlink(saddrname);
  507. name->sun_family = AF_UNIX;
  508. strcpy(name->sun_path, saddrname);
  509. int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
  510. if (sockfd == -1) {
  511. log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
  512. free(name);
  513. return false;
  514. }
  515. if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
  516. log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
  517. close(sockfd);
  518. free(name);
  519. return false;
  520. }
  521. free(name);
  522. // POSIX (1003.1, 2013) says that fchown and fchmod don't necesarily work on sockets. We have to
  523. // use chown and chmod instead.
  524. if (chown(saddrname, socket_uid, socket_gid)) {
  525. log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
  526. close(sockfd);
  527. return false;
  528. }
  529. if (chmod(saddrname, socket_perms) == -1) {
  530. log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
  531. close(sockfd);
  532. return false;
  533. }
  534. if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
  535. log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
  536. close(sockfd);
  537. return false;
  538. }
  539. socket_fd = sockfd;
  540. return true;
  541. }
  542. void ServiceRecord::allDepsStarted(bool has_console) noexcept
  543. {
  544. if (onstart_flags.starts_on_console && ! has_console) {
  545. waiting_for_deps = true;
  546. queueForConsole();
  547. return;
  548. }
  549. waiting_for_deps = false;
  550. if (! open_socket()) {
  551. failed_to_start();
  552. }
  553. bool start_success = start_ps_process();
  554. if (! start_success) {
  555. failed_to_start();
  556. }
  557. }
  558. void ServiceRecord::acquiredConsole() noexcept
  559. {
  560. if (service_state != ServiceState::STARTING) {
  561. // We got the console but no longer want it.
  562. releaseConsole();
  563. }
  564. else if (startCheckDependencies(false)) {
  565. allDepsStarted(true);
  566. }
  567. else {
  568. // We got the console but can't use it yet.
  569. releaseConsole();
  570. }
  571. }
  572. bool bgproc_service::read_pid_file() noexcept
  573. {
  574. const char *pid_file_c = pid_file.c_str();
  575. int fd = open(pid_file_c, O_CLOEXEC);
  576. if (fd != -1) {
  577. char pidbuf[21]; // just enought to hold any 64-bit integer
  578. int r = read(fd, pidbuf, 20);
  579. if (r > 0) {
  580. pidbuf[r] = 0; // store nul terminator
  581. pid = std::atoi(pidbuf);
  582. if (kill(pid, 0) == 0) {
  583. child_listener.add_watch(eventLoop, pid);
  584. }
  585. else {
  586. log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
  587. pid = -1;
  588. close(fd);
  589. return false;
  590. }
  591. }
  592. close(fd);
  593. return true;
  594. }
  595. else {
  596. log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
  597. return false;
  598. }
  599. }
  600. void ServiceRecord::started() noexcept
  601. {
  602. if (onstart_flags.starts_on_console && ! onstart_flags.runs_on_console) {
  603. tcsetpgrp(0, getpgrp());
  604. releaseConsole();
  605. }
  606. logServiceStarted(service_name);
  607. service_state = ServiceState::STARTED;
  608. notifyListeners(ServiceEvent::STARTED);
  609. if (onstart_flags.rw_ready) {
  610. open_control_socket();
  611. }
  612. if (onstart_flags.log_ready) {
  613. setup_external_log();
  614. }
  615. if (force_stop || desired_state == ServiceState::STOPPED) {
  616. // We must now stop.
  617. service_set->addToStopQueue(this);
  618. return;
  619. }
  620. // Notify any dependents whose desired state is STARTED:
  621. for (auto i = dependents.begin(); i != dependents.end(); i++) {
  622. (*i)->dependencyStarted();
  623. }
  624. for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
  625. (*i)->getFrom()->dependencyStarted();
  626. }
  627. }
  628. void ServiceRecord::failed_to_start(bool depfailed) noexcept
  629. {
  630. if (!depfailed && onstart_flags.starts_on_console) {
  631. tcsetpgrp(0, getpgrp());
  632. releaseConsole();
  633. }
  634. logServiceFailed(service_name);
  635. service_state = ServiceState::STOPPED;
  636. if (start_explicit) {
  637. start_explicit = false;
  638. release();
  639. }
  640. notifyListeners(ServiceEvent::FAILEDSTART);
  641. // Cancel start of dependents:
  642. for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
  643. if ((*i)->service_state == ServiceState::STARTING) {
  644. (*i)->prop_failure = true;
  645. service_set->addToPropQueue(*i);
  646. }
  647. }
  648. for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
  649. // We can send 'start', because this is only a soft dependency.
  650. // Our startup failure means that they don't have to wait for us.
  651. if ((*i)->waiting_on) {
  652. (*i)->holding_acq = false;
  653. (*i)->waiting_on = false;
  654. (*i)->getFrom()->dependencyStarted();
  655. release();
  656. }
  657. }
  658. }
  659. bool ServiceRecord::start_ps_process() noexcept
  660. {
  661. // default implementation: there is no process, so we are started.
  662. started();
  663. return true;
  664. }
  665. bool base_process_service::start_ps_process() noexcept
  666. {
  667. if (restarting) {
  668. restart_ps_process();
  669. return true;
  670. }
  671. else {
  672. return start_ps_process(exec_arg_parts, onstart_flags.runs_on_console);
  673. }
  674. }
  675. bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
  676. {
  677. // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
  678. // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
  679. // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
  680. // is written to the pipe, and the parent can read it.
  681. eventLoop.get_time(last_start_time, clock_type::MONOTONIC);
  682. int pipefd[2];
  683. if (pipe2(pipefd, O_CLOEXEC)) {
  684. log(LogLevel::ERROR, service_name, ": can't create status check pipe: ", strerror(errno));
  685. return false;
  686. }
  687. const char * logfile = this->logfile.c_str();
  688. if (*logfile == 0) {
  689. logfile = "/dev/null";
  690. }
  691. bool child_status_registered = false;
  692. ControlConn *control_conn = nullptr;
  693. int control_socket[2] = {-1, -1};
  694. if (onstart_flags.pass_cs_fd) {
  695. if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
  696. log(LogLevel::ERROR, service_name, ": can't create control socket: ", strerror(errno));
  697. goto out_p;
  698. }
  699. // Make the server side socket close-on-exec:
  700. int fdflags = fcntl(control_socket[0], F_GETFD);
  701. fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
  702. try {
  703. control_conn = new ControlConn(&eventLoop, service_set, control_socket[0]);
  704. }
  705. catch (std::exception &exc) {
  706. log(LogLevel::ERROR, service_name, ": can't launch process; out of memory");
  707. goto out_cs;
  708. }
  709. }
  710. // Set up complete, now fork and exec:
  711. pid_t forkpid;
  712. try {
  713. child_status_listener.add_watch(eventLoop, pipefd[0], IN_EVENTS);
  714. child_status_registered = true;
  715. forkpid = child_listener.fork(eventLoop);
  716. }
  717. catch (std::exception &e) {
  718. log(LogLevel::ERROR, service_name, ": Could not fork: ", e.what());
  719. goto out_cs_h;
  720. }
  721. if (forkpid == 0) {
  722. run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
  723. }
  724. else {
  725. // Parent process
  726. close(pipefd[1]); // close the 'other end' fd
  727. if (control_socket[1] != -1) {
  728. close(control_socket[1]);
  729. }
  730. pid = forkpid;
  731. waiting_for_execstat = true;
  732. return true;
  733. }
  734. // Failure exit:
  735. out_cs_h:
  736. if (child_status_registered) {
  737. child_status_listener.deregister(eventLoop);
  738. }
  739. if (onstart_flags.pass_cs_fd) {
  740. delete control_conn;
  741. out_cs:
  742. close(control_socket[0]);
  743. close(control_socket[1]);
  744. }
  745. out_p:
  746. close(pipefd[0]);
  747. close(pipefd[1]);
  748. return false;
  749. }
  750. void ServiceRecord::run_child_proc(const char * const *args, const char *logfile, bool on_console,
  751. int wpipefd, int csfd) noexcept
  752. {
  753. // Child process. Must not allocate memory (or otherwise risk throwing any exception)
  754. // from here until exit().
  755. // If the console already has a session leader, presumably it is us. On the other hand
  756. // if it has no session leader, and we don't create one, then control inputs such as
  757. // ^C will have no effect.
  758. bool do_set_ctty = (tcgetsid(0) == -1);
  759. // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
  760. // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
  761. sigset_t sigwait_set;
  762. sigset_t sigall_set;
  763. sigfillset(&sigall_set);
  764. sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
  765. sigdelset(&sigwait_set, SIGCHLD);
  766. sigdelset(&sigwait_set, SIGINT);
  767. sigdelset(&sigwait_set, SIGTERM);
  768. constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
  769. // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
  770. // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
  771. // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
  772. char nbuf[bufsz];
  773. // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
  774. constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
  775. char csenvbuf[csenvbufsz];
  776. int minfd = (socket_fd == -1) ? 3 : 4;
  777. // Move wpipefd/csfd to another fd if necessary
  778. if (wpipefd < minfd) {
  779. wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
  780. if (wpipefd == -1) goto failure_out;
  781. }
  782. if (csfd != -1 && csfd < minfd) {
  783. csfd = fcntl(csfd, F_DUPFD, minfd);
  784. if (csfd == -1) goto failure_out;
  785. }
  786. if (socket_fd != -1) {
  787. if (dup2(socket_fd, 3) == -1) goto failure_out;
  788. if (socket_fd != 3) {
  789. close(socket_fd);
  790. }
  791. if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
  792. snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
  793. if (putenv(nbuf)) goto failure_out;
  794. }
  795. if (csfd != -1) {
  796. snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
  797. if (putenv(csenvbuf)) goto failure_out;
  798. }
  799. if (! on_console) {
  800. // Re-set stdin, stdout, stderr
  801. close(0); close(1); close(2);
  802. if (open("/dev/null", O_RDONLY) == 0) {
  803. // stdin = 0. That's what we should have; proceed with opening
  804. // stdout and stderr.
  805. if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
  806. goto failure_out;
  807. }
  808. if (dup2(1, 2) != 2) {
  809. goto failure_out;
  810. }
  811. }
  812. else goto failure_out;
  813. // We have the option of creating a new process group and/or session. If
  814. // we just create a new process group, the child process cannot make itself
  815. // a session leader if it wants to do that (eg getty/login will generally
  816. // want this). If we do neither, and we are running with a controlling
  817. // terminal, a ^C or similar will also affect the child process.
  818. setsid();
  819. }
  820. else {
  821. // "run on console" - run as a foreground job on the terminal/console device
  822. // if do_set_ctty is false, we are the session leader; we are probably running
  823. // as a user process. Don't create a new session leader in that case, and run
  824. // as part of the parent session. Otherwise, the new session cannot claim the
  825. // terminal as a controlling terminal (it is already claimed), meaning that it
  826. // will not see control signals from ^C etc.
  827. if (do_set_ctty) {
  828. // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
  829. signal(SIGTSTP, SIG_IGN);
  830. // Become session leader
  831. setsid();
  832. ioctl(0, TIOCSCTTY, 0);
  833. }
  834. setpgid(0,0);
  835. tcsetpgrp(0, getpgrp());
  836. }
  837. sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
  838. execvp(args[0], const_cast<char **>(args));
  839. // If we got here, the exec failed:
  840. failure_out:
  841. int exec_status = errno;
  842. write(wpipefd, &exec_status, sizeof(int));
  843. _exit(0);
  844. }
  845. // Mark this and all dependent services as force-stopped.
  846. void ServiceRecord::forceStop() noexcept
  847. {
  848. if (service_state != ServiceState::STOPPED) {
  849. force_stop = true;
  850. service_set->addToStopQueue(this);
  851. }
  852. }
  853. void ServiceRecord::dependentStopped() noexcept
  854. {
  855. if (service_state == ServiceState::STOPPING && waiting_for_deps) {
  856. service_set->addToPropQueue(this);
  857. }
  858. }
  859. void ServiceRecord::stop(bool bring_down) noexcept
  860. {
  861. if (start_explicit) {
  862. start_explicit = false;
  863. release();
  864. }
  865. if (bring_down && desired_state != ServiceState::STOPPED) {
  866. desired_state = ServiceState::STOPPED;
  867. service_set->addToStopQueue(this);
  868. }
  869. }
  870. void ServiceRecord::do_stop() noexcept
  871. {
  872. if (pinned_started) return;
  873. if (service_state != ServiceState::STARTED) {
  874. if (service_state == ServiceState::STARTING) {
  875. if (! can_interrupt_start()) {
  876. // Well this is awkward: we're going to have to continue
  877. // starting, but we don't want any dependents to think that
  878. // they are still waiting to start.
  879. // Make sure they remain stopped:
  880. stopDependents();
  881. return;
  882. }
  883. // We must have had desired_state == STARTED.
  884. notifyListeners(ServiceEvent::STARTCANCELLED);
  885. // Reaching this point, we have can_interrupt_start() == true. So,
  886. // we can stop. Dependents might be starting, but they must be
  887. // waiting on us, so they should also be immediately stoppable.
  888. // Fall through to below,.
  889. }
  890. else {
  891. // If we're starting we need to wait for that to complete.
  892. // If we're already stopping/stopped there's nothing to do.
  893. return;
  894. }
  895. }
  896. service_state = ServiceState::STOPPING;
  897. waiting_for_deps = true;
  898. // If we get here, we are in STARTED state; stop all dependents.
  899. if (stopDependents()) {
  900. all_deps_stopped();
  901. }
  902. }
  903. bool ServiceRecord::stopCheckDependents() noexcept
  904. {
  905. bool all_deps_stopped = true;
  906. for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
  907. if (! (*i)->is_stopped()) {
  908. all_deps_stopped = false;
  909. break;
  910. }
  911. }
  912. return all_deps_stopped;
  913. }
  914. bool ServiceRecord::stopDependents() noexcept
  915. {
  916. bool all_deps_stopped = true;
  917. for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
  918. if (! (*i)->is_stopped()) {
  919. // Note we check *first* since if the dependent service is not stopped,
  920. // 1. We will issue a stop to it shortly and
  921. // 2. It will notify us when stopped, at which point the stopCheckDependents()
  922. // check is run anyway.
  923. all_deps_stopped = false;
  924. }
  925. (*i)->forceStop();
  926. }
  927. return all_deps_stopped;
  928. }
  929. // All dependents have stopped; we can stop now, too. Only called when STOPPING.
  930. void ServiceRecord::all_deps_stopped() noexcept
  931. {
  932. waiting_for_deps = false;
  933. stopped();
  934. }
  935. void base_process_service::all_deps_stopped() noexcept
  936. {
  937. waiting_for_deps = false;
  938. if (pid != -1) {
  939. // The process is still kicking on - must actually kill it.
  940. if (! onstart_flags.no_sigterm) {
  941. kill(pid, SIGTERM);
  942. }
  943. if (term_signal != -1) {
  944. kill(pid, term_signal);
  945. }
  946. // In most cases, the rest is done in process_child_callback.
  947. // If we are a BGPROCESS and the process is not our immediate child, however, that
  948. // won't work - check for this now:
  949. if (service_type == ServiceType::BGPROCESS) {
  950. int status;
  951. pid_t r = waitpid(pid, &status, WNOHANG);
  952. if (r == -1 && errno == ECHILD) {
  953. // We can't track this child (or it's terminated already)
  954. stopped();
  955. }
  956. else if (r == pid) {
  957. // Process may have died due to signal since we explicitly requested it to
  958. // stop by signalling it; no need to log any termination status.
  959. stopped();
  960. }
  961. }
  962. }
  963. else {
  964. // The process is already dead.
  965. stopped();
  966. }
  967. }
  968. void scripted_service::all_deps_stopped() noexcept
  969. {
  970. waiting_for_deps = false;
  971. if (stop_command.length() == 0) {
  972. stopped();
  973. }
  974. else if (! start_ps_process(stop_arg_parts, false)) {
  975. // Couldn't execute stop script, but there's not much we can do:
  976. stopped();
  977. }
  978. }
  979. void ServiceRecord::unpin() noexcept
  980. {
  981. if (pinned_started) {
  982. pinned_started = false;
  983. if (desired_state == ServiceState::STOPPED) {
  984. do_stop();
  985. service_set->processQueues(false);
  986. }
  987. }
  988. if (pinned_stopped) {
  989. pinned_stopped = false;
  990. if (desired_state == ServiceState::STARTED) {
  991. do_start();
  992. service_set->processQueues(true);
  993. }
  994. }
  995. }
  996. void ServiceRecord::queueForConsole() noexcept
  997. {
  998. service_set->append_console_queue(this);
  999. }
  1000. void ServiceRecord::releaseConsole() noexcept
  1001. {
  1002. service_set->pullConsoleQueue();
  1003. }
  1004. void ServiceSet::service_active(ServiceRecord *sr) noexcept
  1005. {
  1006. active_services++;
  1007. }
  1008. void ServiceSet::service_inactive(ServiceRecord *sr) noexcept
  1009. {
  1010. active_services--;
  1011. }
  1012. base_process_service::base_process_service(ServiceSet *sset, string name, ServiceType service_type, string &&command,
  1013. std::list<std::pair<unsigned,unsigned>> &command_offsets,
  1014. sr_list * pdepends_on, sr_list * pdepends_soft)
  1015. : ServiceRecord(sset, name, service_type, std::move(command), command_offsets,
  1016. pdepends_on, pdepends_soft), child_listener(this), child_status_listener(this)
  1017. {
  1018. restart_timer.service = this;
  1019. restart_timer.add_timer(eventLoop);
  1020. }
  1021. void base_process_service::restart_ps_process() noexcept
  1022. {
  1023. timespec current_time;
  1024. eventLoop.get_time(current_time, clock_type::MONOTONIC);
  1025. auto tdiff_s = current_time.tv_sec - last_start_time.tv_sec;
  1026. decltype(current_time.tv_nsec) tdiff_ns;
  1027. if (current_time.tv_nsec >= last_start_time.tv_nsec) {
  1028. tdiff_ns = current_time.tv_nsec - last_start_time.tv_nsec;
  1029. }
  1030. else {
  1031. tdiff_s -= 1;
  1032. tdiff_ns = 1000000000 - (last_start_time.tv_nsec - current_time.tv_nsec);
  1033. }
  1034. if (tdiff_s > 0 || tdiff_ns > 200000000) {
  1035. // > 200ms
  1036. restarting = false;
  1037. if (! start_ps_process(exec_arg_parts, onstart_flags.runs_on_console)) {
  1038. // TODO handle appropriately; mark service stopped.
  1039. }
  1040. }
  1041. else {
  1042. timespec timeout;
  1043. timeout.tv_sec = 0;
  1044. timeout.tv_nsec = 200000000 - tdiff_ns;
  1045. restart_timer.arm_timer_rel(eventLoop, timeout);
  1046. }
  1047. }
  1048. dasynq::rearm process_restart_timer::timer_expiry(EventLoop_t &, int expiry_count)
  1049. {
  1050. return service->restart_timer_expired();
  1051. }
  1052. dasynq::rearm base_process_service::restart_timer_expired() noexcept
  1053. {
  1054. // begin starting process:
  1055. if (! start_ps_process(exec_arg_parts, onstart_flags.runs_on_console)) {
  1056. // TODO handle appropriately; mark service stopped.
  1057. }
  1058. return dasynq::rearm::DISARM;
  1059. }