service.h 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  1. #ifndef SERVICE_H
  2. #define SERVICE_H
  3. #include <string>
  4. #include <list>
  5. #include <vector>
  6. #include <csignal>
  7. #include <unordered_set>
  8. #include <algorithm>
  9. #include "dasynq.h"
  10. #include "dinit.h"
  11. #include "control.h"
  12. #include "service-listener.h"
  13. #include "service-constants.h"
  14. #include "load-service.h"
  15. #include "dinit-ll.h"
  16. #include "dinit-log.h"
  17. #include "service-dir.h"
  18. #include "dinit-env.h"
  19. /*
  20. * This header defines service_record, a data record maintaining information about a service,
  21. * and service_set, a set of interdependent service records. It also defines some associated
  22. * types and exceptions.
  23. *
  24. * Service states
  25. * --------------
  26. * Services have both a current state and a desired state. The desired state can be
  27. * either STARTED or STOPPED. The current state can also be STARTING or STOPPING.
  28. * A service can be "pinned" in either the STARTED or STOPPED states to prevent it
  29. * from leaving that state until it is unpinned.
  30. *
  31. * The total state is a combination of the two, current and desired:
  32. * STOPPED/STOPPED : stopped and will remain stopped
  33. * STOPPED/STARTED : stopped (pinned), must be unpinned to start
  34. * STARTING/STARTED : starting, but not yet started. Dependencies may also be starting.
  35. * STARTING/STOPPED : as above, but the service will be stopped again as soon as it has
  36. * completed startup.
  37. * STARTED/STARTED : running and will continue running.
  38. * STARTED/STOPPED : started (pinned), must be unpinned to stop
  39. * STOPPING/STOPPED : stopping and will stop. Dependents may be stopping.
  40. * STOPPING/STARTED : as above, but the service will be re-started again once it stops.
  41. *
  42. * A scripted service is in the STARTING/STOPPING states during the script execution.
  43. * A process service is in the STOPPING state when it has been signalled to stop, and is
  44. * in the STARTING state when waiting for dependencies to start or for the exec() call in
  45. * the forked child to complete and return a status.
  46. *
  47. * Interrupted transitions
  48. * -----------------------
  49. * A service that is STOPPING may be issued a start order, or a service that is STARTING may be
  50. * issued a stop. In some cases a STOPPING or STARTING transition can be interrupted and immediately
  51. * switch to the other kind of transition. We don't normally want to do this if we're waiting on an
  52. * external process, since simply killing that process might leave a mess. However, if a service is
  53. * waiting for its dependencies or dependents, its start or stop can usually be interrupted.
  54. *
  55. * Acquisition/release:
  56. * ------------------
  57. * Each service has a dependent-count ("required_by"). This starts at 0, adds 1 if the service has
  58. * explicitly been started (i.e. "start_explicit" is true), and adds 1 for each dependent service
  59. * which is not STOPPED/STOPPING (including dependents via a "soft" dependency relationship).
  60. * When required_by transitions to 0, the service is stopped and it will release its own dependencies
  61. * (unless it is pinned started). Conversely, when required_by transitions from 0 to 1, the service is
  62. * started and dependencies will be required (unless pinned stopped).
  63. *
  64. * In general, therefore, the dependent-count determines the target state (STARTED if the count is greater
  65. * than 0, otherwise STOPPED). Explicit activation counts effectively increments the count and sets the
  66. * target state as STARTED.
  67. *
  68. * An exception is that setting the target state to STOPPED is used to inhibit restart. This is propagated
  69. * to dependent services (i.e. their target state will also be set to STOPPED). The required_by count for a
  70. * service in this scenario will settle to 0 anyway (because dependents will be stopped).
  71. *
  72. * Another exception is that a service may become STOPPED while it is still required (for example if a
  73. * process terminates unexpectedly). This will force hard dependents to stop also, so again, the required_by
  74. * count will settle to 0, unless the service is active and set to auto-restart (or a dependent is).
  75. *
  76. * When a service stops, any soft dependency links to its dependents must be broken, or otherwise the
  77. * target state will remain as STARTED and the service will always restart. If the auto-restart option is
  78. * enabled for the service, or if the service is explicitly being restarted (restart == true), this is
  79. * actually the desired behaviour, and so in these cases the dependency links are not broken.
  80. *
  81. * Force stop
  82. * ----------
  83. * A service can be issued a stop-and-take down order (via `stop(true)'); this will first stop
  84. * dependent services, which may restart and cancel the stop of the former service. However, a
  85. * service can be force-stopped, which means that its stop process cannot be cancelled (though
  86. * it may still be put in a desired state of STARTED, meaning it will start immediately upon
  87. * stopping). Force-stop is achieved via a flag in the service record which is checked before
  88. * interrupting a stop operation.
  89. *
  90. * Pinning
  91. * -------
  92. * A service may be "pinned" in either STARTED or STOPPED states (or even both). Once it
  93. * reaches a pinned state, a service will not leave that state. A service that is pinned
  94. * STOPPED cannot be started or marked active and any attempt to start it will fail. A service
  95. * that is pinned STARTED remains started even if the service is not marked active and no other
  96. * active service depends on it; this is the only scenario in which a service with a required_by
  97. * count of 0 will remain started. Once unpinned the service will stop.
  98. *
  99. * (Note that pinning prevents, but never causes, state transition).
  100. *
  101. * The priority of the different state deciders is:
  102. * - pins
  103. * - force stop flag
  104. * - desired state (which is manipulated by require/release operations)
  105. *
  106. * So a forced stop cannot occur until the service is not pinned started, for instance. (if
  107. * pinned, the forced stop remains pending until the pin is released).
  108. *
  109. * Two-phase transition
  110. * --------------------
  111. * Transition between states occurs in two phases: propagation and execution. In both phases
  112. * a linked-list queue is used to keep track of which services need processing; this avoids
  113. * recursion (which would be of unknown depth and therefore liable to cause stack overflow).
  114. *
  115. * In the propagation phase, acquisition/release messages are processed, and desired state may be
  116. * altered accordingly. Start and stop requests are also propagated in this phase. The state may
  117. * be set to STARTING or STOPPING to reflect the desired state, but will never be set to STARTED
  118. * or STOPPED (that happens in the execution phase).
  119. *
  120. * The two-phase transition is needed to avoid problem where a service that becomes STOPPED has
  121. * an incorrect acquisition count, which may cause it to restart when it should not. The
  122. * propagation phase allows the acquisition count to settle before the transition to the STOPPED
  123. * state occurs, and the decision whether to restart can then be made based on the (correct)
  124. * acquisition count. See "acquisition/release" above for details of when this can occur.
  125. *
  126. * Propagation variables:
  127. * prop_acquire: the service has transitioned to an acquired state and must issue an acquire
  128. * on its dependencies
  129. * prop_release: the service has transitioned to a released state and must issue a release on
  130. * its dependencies.
  131. *
  132. * prop_start: the service should start
  133. * prop_stop: the service should stop
  134. *
  135. * Note that "prop_acquire"/"prop_release" form a pair which cannot both be set at the same time
  136. * which is enforced via explicit checks. For "prop_start"/"prop_stop" this occurs implicitly.
  137. *
  138. * In the execution phase, actions are taken to achieve the desired state. Actual state may
  139. * transition according to the current and desired states. Processes can be sent signals, etc
  140. * in order to stop them.
  141. */
  142. class service_record;
  143. class service_set;
  144. class base_process_service;
  145. /* Service dependency record */
  146. class service_dep
  147. {
  148. service_record * from;
  149. service_record * to;
  150. public:
  151. /* Whether the 'from' service is waiting for the 'to' service to start */
  152. bool waiting_on;
  153. /* Whether the 'from' service is holding an acquire on the 'to' service */
  154. bool holding_acq;
  155. const dependency_type dep_type;
  156. // Check if the dependency is a hard dependency (including milestone still waiting).
  157. bool is_hard()
  158. {
  159. return dep_type == dependency_type::REGULAR
  160. || (dep_type == dependency_type::MILESTONE && waiting_on);
  161. }
  162. // Check if the dependency represents only an ordering constraint (not really a dependency)
  163. bool is_only_ordering()
  164. {
  165. return (dep_type == dependency_type::BEFORE) || (dep_type == dependency_type::AFTER);
  166. }
  167. service_dep(service_record * from, service_record * to, dependency_type dep_type_p) noexcept
  168. : from(from), to(to), waiting_on(false), holding_acq(false), dep_type(dep_type_p)
  169. { }
  170. service_dep(const service_dep &) = delete;
  171. void operator=(const service_dep &) = delete;
  172. service_record * get_from() const noexcept
  173. {
  174. return from;
  175. }
  176. service_record * get_to() const noexcept
  177. {
  178. return to;
  179. }
  180. void set_to(service_record *new_to) noexcept
  181. {
  182. to = new_to;
  183. }
  184. };
  185. /* preliminary service dependency information */
  186. class prelim_dep
  187. {
  188. public:
  189. service_record * const to;
  190. dependency_type const dep_type;
  191. prelim_dep(service_record *to_p, dependency_type dep_type_p) : to(to_p), dep_type(dep_type_p)
  192. {
  193. // (constructor)
  194. }
  195. };
  196. // log a service load exception
  197. inline void log_service_load_failure(service_description_exc &exc)
  198. {
  199. if (exc.line_num != (unsigned)-1) {
  200. log(loglevel_t::ERROR, "Couldn't load service '", exc.service_name, "' (line ", exc.line_num, "): ",
  201. exc.exc_description);
  202. }
  203. else {
  204. log(loglevel_t::ERROR, "Couldn't load service '", exc.service_name, "' setting '", exc.setting_name, "': ",
  205. exc.exc_description);
  206. }
  207. }
  208. // service_record: base class for service record containing static information
  209. // and current state of each service.
  210. //
  211. // This abstract base class defines the dependency behaviour of services. The actions to actually bring a
  212. // service up or down are specified by subclasses in the virtual methods (see especially bring_up() and
  213. // bring_down()).
  214. //
  215. class service_record
  216. {
  217. protected:
  218. using string = std::string;
  219. using time_val = dasynq::time_val;
  220. private:
  221. string service_name;
  222. service_type_t record_type; // service_type_t::DUMMY, PROCESS, SCRIPTED, or INTERNAL
  223. // 'service_state' can be any valid state: STARTED, STARTING, STOPPING, STOPPED.
  224. // 'desired_state' is only set to final states: STARTED or STOPPED.
  225. service_state_t service_state = service_state_t::STOPPED;
  226. service_state_t desired_state = service_state_t::STOPPED;
  227. protected:
  228. service_flags_t onstart_flags;
  229. environment service_env; // holds the environment populated during load
  230. bool auto_restart : 1; // whether to restart this (process) if it dies unexpectedly
  231. bool smooth_recovery : 1; // whether the service process can restart without bringing down service
  232. // Pins. Start pins are directly transitive (hence pinned_started and dept_pinned_started) whereas
  233. // for stop pins, the effect is transitive since a stop-pinned service will "fail" to start anyway.
  234. bool pinned_stopped : 1;
  235. bool pinned_started : 1;
  236. bool dept_pinned_started : 1; // pinned started due to dependent
  237. bool waiting_for_deps : 1; // if STARTING, whether we are waiting for dependencies/console
  238. // if STOPPING, whether we are waiting for dependents to stop
  239. bool waiting_for_console : 1; // waiting for exclusive console access (while STARTING)
  240. bool have_console : 1; // whether we have exclusive console access (STARTING/STARTED)
  241. bool waiting_for_execstat : 1; // if we are waiting for exec status after fork()
  242. bool start_explicit : 1; // whether we are are explicitly required to be started
  243. bool prop_require : 1; // require must be propagated
  244. bool prop_release : 1; // release must be propagated
  245. bool prop_failure : 1; // failure to start must be propagated
  246. bool prop_start : 1;
  247. bool prop_stop : 1;
  248. bool prop_pin_dpt : 1;
  249. bool start_failed : 1; // failed to start (reset when begins starting)
  250. bool start_skipped : 1; // start was skipped by interrupt
  251. bool in_auto_restart : 1;
  252. bool in_user_restart : 1;
  253. int required_by = 0; // number of dependents wanting this service to be started
  254. // list of dependencies
  255. typedef std::list<service_dep> dep_list;
  256. // list of dependents
  257. typedef std::list<service_dep *> dpt_list;
  258. dep_list depends_on; // services this one depends on
  259. dpt_list dependents; // services depending on this one
  260. service_set *services; // the set this service belongs to
  261. std::unordered_set<service_listener *> listeners;
  262. // Process services:
  263. bool force_stop; // true if the service must actually stop. This is the
  264. // case if for example the process dies; the service,
  265. // and all its dependencies, MUST be stopped.
  266. int term_signal = SIGTERM; // signal to use for process termination
  267. string socket_path; // path to the socket for socket-activation service
  268. int socket_perms; // socket permissions ("mode")
  269. uid_t socket_uid = -1; // socket user id or -1
  270. gid_t socket_gid = -1; // socket group id or -1
  271. stopped_reason_t stop_reason = stopped_reason_t::NORMAL; // reason why stopped
  272. string start_on_completion; // service to start when this one completes
  273. // Data for use by service_set
  274. public:
  275. // Console queue.
  276. lld_node<service_record> console_queue_node;
  277. // Propagation and start/stop queues
  278. lls_node<service_record> prop_queue_node;
  279. lls_node<service_record> stop_queue_node;
  280. protected:
  281. // Service has actually stopped (includes having all dependents
  282. // reaching STOPPED state).
  283. void stopped() noexcept;
  284. // Service has successfully started
  285. void started() noexcept;
  286. // Service failed to start (should be called with state set to STOPPING or STOPPED).
  287. // dep_failed: whether failure is recorded due to a dependency failing
  288. // immediate_stop: whether to set state as STOPPED and handle complete stop.
  289. void failed_to_start(bool dep_failed = false, bool immediate_stop = true) noexcept;
  290. // Service stopped (failed), unrecoverably; dependents should not auto-restart
  291. void unrecoverable_stop() noexcept;
  292. // A dependency has reached STARTED state
  293. void dependency_started() noexcept;
  294. void all_deps_started() noexcept;
  295. // Start all dependencies, return true if all have started
  296. bool start_check_dependencies() noexcept;
  297. // Check whether all dependencies have started (i.e. whether we can start now)
  298. bool check_deps_started() noexcept;
  299. // Whether a STOPPING service can immediately transition to STARTED.
  300. bool can_interrupt_stop() noexcept
  301. {
  302. return waiting_for_deps && ! force_stop;
  303. }
  304. // A dependent has reached STOPPED state
  305. void dependent_stopped() noexcept;
  306. // check if all dependents have stopped
  307. bool stop_check_dependents() noexcept;
  308. // issue a stop to all dependents, return true if they are all already stopped
  309. bool stop_dependents(bool with_restart, bool for_restart) noexcept;
  310. // issue a restart to all hard dependents
  311. bool restart_dependents() noexcept;
  312. void require() noexcept;
  313. void release(bool issue_stop = true) noexcept;
  314. void release_dependencies() noexcept;
  315. // Check if service is, fundamentally, stopped. It is either in the stopped state, or
  316. // starting but waiting for dependents, i.e. it can be trivially set to stopped state.
  317. bool is_fundamentally_stopped() noexcept
  318. {
  319. return service_state == service_state_t::STOPPED
  320. || (service_state == service_state_t::STARTING && waiting_for_deps);
  321. }
  322. void notify_listeners(service_event_t event) noexcept
  323. {
  324. for (auto l : listeners) {
  325. l->service_event(this, event);
  326. }
  327. }
  328. // Queue to run on the console. 'acquired_console()' will be called when the console is available.
  329. // Has no effect if the service has already queued for console.
  330. void queue_for_console() noexcept;
  331. // Release console (console must be currently held by this service)
  332. void release_console() noexcept;
  333. // Started state reached
  334. bool process_started() noexcept;
  335. // Initiate definite startup
  336. void initiate_start() noexcept;
  337. // Called on transition of desired state from stopped to started (or unpinned stop)
  338. void do_start() noexcept;
  339. // Begin stopping, release activation.
  340. void do_stop(bool with_restart = false) noexcept;
  341. // Set the service state
  342. void set_state(service_state_t new_state) noexcept
  343. {
  344. service_state = new_state;
  345. }
  346. // Virtual functions, to be implemented by service implementations:
  347. // Do any post-dependency startup; return false on failure. Should return true if service
  348. // has started or is in the process of starting.
  349. virtual bool bring_up() noexcept;
  350. // All dependents have stopped, and this service should proceed to stop.
  351. virtual void bring_down() noexcept;
  352. // Whether a STARTING service can immediately transition to STOPPED (as opposed to
  353. // having to wait for it reach STARTED and then go through STOPPING). Note that the
  354. // waiting_for_deps flag being set may override this check.
  355. virtual bool can_interrupt_start() noexcept
  356. {
  357. return waiting_for_deps;
  358. }
  359. // Interrupt startup. Returns true if service start is fully cancelled; returns false if cancel order
  360. // issued but service has not yet responded (state will be set to STOPPING).
  361. virtual bool interrupt_start() noexcept;
  362. // The service is becoming inactive - i.e. it has stopped and will not be immediately restarted. Perform
  363. // any appropriate cleanup.
  364. virtual void becoming_inactive() noexcept { }
  365. // Check whether the service should automatically restart (assuming auto_restart is true)
  366. virtual bool check_restart() noexcept
  367. {
  368. return true;
  369. }
  370. public:
  371. service_record(service_set *set, const string &name)
  372. : service_name(name), service_state(service_state_t::STOPPED),
  373. desired_state(service_state_t::STOPPED), auto_restart(false), smooth_recovery(false),
  374. pinned_stopped(false), pinned_started(false), dept_pinned_started(false),
  375. waiting_for_deps(false), waiting_for_console(false), have_console(false),
  376. waiting_for_execstat(false), start_explicit(false), prop_require(false), prop_release(false),
  377. prop_failure(false), prop_start(false), prop_stop(false), prop_pin_dpt(false),
  378. start_failed(false), start_skipped(false), in_auto_restart(false), in_user_restart(false),
  379. force_stop(false)
  380. {
  381. services = set;
  382. record_type = service_type_t::DUMMY;
  383. socket_perms = 0;
  384. }
  385. service_record(service_set *set, const string &name, service_type_t record_type_p,
  386. const std::list<prelim_dep> &deplist_p)
  387. : service_record(set, name)
  388. {
  389. services = set;
  390. service_name = name;
  391. this->record_type = record_type_p;
  392. try {
  393. for (auto & pdep : deplist_p) {
  394. auto b = depends_on.emplace(depends_on.end(), this, pdep.to, pdep.dep_type);
  395. try {
  396. pdep.to->dependents.push_back(&(*b));
  397. }
  398. catch (...) {
  399. // we'll roll back one now and re-throw:
  400. depends_on.pop_back();
  401. throw;
  402. }
  403. }
  404. }
  405. catch (...) {
  406. for (auto & dep : depends_on) {
  407. dep.get_to()->dependents.pop_back();
  408. }
  409. throw;
  410. }
  411. }
  412. service_record(const service_record &) = delete;
  413. void operator=(const service_record &) = delete;
  414. virtual ~service_record() noexcept
  415. {
  416. }
  417. // Get the type of this service record
  418. service_type_t get_type() noexcept
  419. {
  420. return record_type;
  421. }
  422. // begin transition from stopped to started state or vice versa depending on current and desired state
  423. void execute_transition() noexcept;
  424. void do_propagation() noexcept;
  425. // Console is available.
  426. void acquired_console() noexcept;
  427. // Get the target (aka desired) state.
  428. service_state_t get_target_state() noexcept
  429. {
  430. return desired_state;
  431. }
  432. // Is the service explicitly marked active?
  433. bool is_marked_active() noexcept
  434. {
  435. return start_explicit;
  436. }
  437. void set_environment(environment &&env) noexcept
  438. {
  439. this->service_env = std::move(env);
  440. }
  441. // Set whether this service should automatically restart when it dies
  442. void set_auto_restart(bool auto_restart) noexcept
  443. {
  444. this->auto_restart = auto_restart;
  445. }
  446. void set_smooth_recovery(bool smooth_recovery) noexcept
  447. {
  448. this->smooth_recovery = smooth_recovery;
  449. }
  450. // Set "on start" flags (commands)
  451. void set_flags(service_flags_t flags) noexcept
  452. {
  453. this->onstart_flags = flags;
  454. }
  455. service_flags_t get_flags() noexcept
  456. {
  457. return onstart_flags;
  458. }
  459. void set_socket_details(string &&socket_path, int socket_perms, uid_t socket_uid, uid_t socket_gid)
  460. noexcept
  461. {
  462. this->socket_path = std::move(socket_path);
  463. this->socket_perms = socket_perms;
  464. this->socket_uid = socket_uid;
  465. this->socket_gid = socket_gid;
  466. }
  467. // Set the service that this one "chains" to. When this service completes, the named service is started.
  468. void set_chain_to(string &&chain_to) noexcept
  469. {
  470. start_on_completion = std::move(chain_to);
  471. }
  472. const std::string &get_name() const noexcept { return service_name; }
  473. service_state_t get_state() const noexcept { return service_state; }
  474. void start() noexcept; // start the service
  475. void stop(bool bring_down = true) noexcept; // stop the service
  476. bool restart() noexcept; // restart the service, returns true iff restart issued
  477. void forced_stop() noexcept; // force-stop this service and all dependents
  478. // Pin the service in "started" state (when it reaches the state)
  479. void pin_start() noexcept;
  480. // Pin the service in "stopped" state (when it reaches the state)
  481. void pin_stop() noexcept
  482. {
  483. pinned_stopped = true;
  484. }
  485. // Remove both "started" and "stopped" pins. If the service is currently pinned
  486. // in either state but would naturally be in the opposite state, it will immediately
  487. // commence starting/stopping.
  488. void unpin() noexcept;
  489. bool is_start_pinned() noexcept
  490. {
  491. return pinned_started || dept_pinned_started;
  492. }
  493. bool is_stop_pinned() noexcept
  494. {
  495. return pinned_stopped;
  496. }
  497. // Is this a dummy service (used only when loading a new service)?
  498. bool is_dummy() noexcept
  499. {
  500. return record_type == service_type_t::DUMMY;
  501. }
  502. bool did_start_fail() noexcept
  503. {
  504. return start_failed;
  505. }
  506. bool was_start_skipped() noexcept
  507. {
  508. return start_skipped;
  509. }
  510. // Add a listener. A listener must only be added once. May throw std::bad_alloc.
  511. void add_listener(service_listener * listener)
  512. {
  513. listeners.insert(listener);
  514. }
  515. // Remove a listener.
  516. void remove_listener(service_listener * listener) noexcept
  517. {
  518. listeners.erase(listener);
  519. }
  520. // Assuming there is one reference (from a control link), return true if this is the only reference,
  521. // or false if there are others (including dependents).
  522. bool has_lone_ref(bool check_deps = true) noexcept
  523. {
  524. if (check_deps) {
  525. for (auto *dept : dependents) {
  526. // BEFORE links don't count because they are actually specified via the "to" service i.e.
  527. // this service.
  528. if (dept->dep_type != dependency_type::BEFORE) {
  529. return false;
  530. }
  531. }
  532. }
  533. auto i = listeners.begin();
  534. return (++i == listeners.end());
  535. }
  536. // Prepare this service to be unloaded.
  537. void prepare_for_unload() noexcept
  538. {
  539. // Remove all dependencies:
  540. for (auto &dep : depends_on) {
  541. auto &dep_dpts = dep.get_to()->dependents;
  542. dep_dpts.erase(std::find(dep_dpts.begin(), dep_dpts.end(), &dep));
  543. }
  544. depends_on.clear();
  545. // Also remove all dependents. This should not be necessary except for "before" links.
  546. // Note: this for loop might look odd, but it's correct!
  547. for (auto i = dependents.begin(); i != dependents.end(); i = dependents.begin()) {
  548. (*i)->get_from()->rm_dep(**i);
  549. }
  550. }
  551. // Why did the service stop?
  552. stopped_reason_t get_stop_reason()
  553. {
  554. return stop_reason;
  555. }
  556. bool is_waiting_for_console()
  557. {
  558. return waiting_for_console;
  559. }
  560. bool has_console()
  561. {
  562. return have_console;
  563. }
  564. virtual pid_t get_pid()
  565. {
  566. return -1;
  567. }
  568. virtual int get_exit_status()
  569. {
  570. return 0;
  571. }
  572. dep_list & get_dependencies()
  573. {
  574. return depends_on;
  575. }
  576. dpt_list & get_dependents()
  577. {
  578. return dependents;
  579. }
  580. // Add a dependency. Caller must ensure that the services are in an appropriate state and that
  581. // a circular dependency chain is not created. Propagation queues should be processed after
  582. // calling this (if dependency may be required to start). May throw std::bad_alloc.
  583. service_dep & add_dep(service_record *to, dependency_type dep_type)
  584. {
  585. return add_dep(to, dep_type, depends_on.end());
  586. }
  587. // Add a dependency. Caller must ensure that the services are in an appropriate state and that
  588. // a circular dependency chain is not created. Propagation queues should be processed after
  589. // calling this (if dependency may be required to start). May throw std::bad_alloc.
  590. // i - where to insert the dependency (in dependencies list)
  591. service_dep & add_dep(service_record *to, dependency_type dep_type, dep_list::iterator i)
  592. {
  593. auto pre_i = depends_on.emplace(i, this, to, dep_type);
  594. try {
  595. to->dependents.push_back(&(*pre_i));
  596. }
  597. catch (...) {
  598. depends_on.erase(pre_i);
  599. throw;
  600. }
  601. if (dep_type != dependency_type::BEFORE && dep_type != dependency_type::AFTER) {
  602. if (dep_type == dependency_type::REGULAR
  603. || to->get_state() == service_state_t::STARTED
  604. || to->get_state() == service_state_t::STARTING) {
  605. if (service_state == service_state_t::STARTING
  606. || service_state == service_state_t::STARTED) {
  607. to->require();
  608. pre_i->holding_acq = true;
  609. }
  610. }
  611. }
  612. return *pre_i;
  613. }
  614. // Remove a dependency, of the given type, to the given service. Returns true if the specified
  615. // dependency was found (and removed). Propagation queues should be processed after calling.
  616. bool rm_dep(service_record *to, dependency_type dep_type) noexcept
  617. {
  618. for (auto i = depends_on.begin(); i != depends_on.end(); ++i) {
  619. auto & dep = *i;
  620. if (dep.get_to() == to && dep.dep_type == dep_type) {
  621. rm_dep(i);
  622. return true;
  623. }
  624. }
  625. return false;
  626. }
  627. void rm_dep(service_dep &dep) noexcept
  628. {
  629. for (auto i = depends_on.begin(); i != depends_on.end(); ++i) {
  630. if (&(*i) == &dep) {
  631. rm_dep(i);
  632. return;
  633. }
  634. }
  635. }
  636. dep_list::iterator rm_dep(dep_list::iterator i) noexcept
  637. {
  638. auto to = i->get_to();
  639. for (auto j = to->dependents.begin(); ; ++j) {
  640. if (*j == &(*i)) {
  641. to->dependents.erase(j);
  642. break;
  643. }
  644. }
  645. if (i->holding_acq) {
  646. to->release();
  647. }
  648. return depends_on.erase(i);
  649. }
  650. // Start a specific dependency of this service. Should only be called if this service is in an
  651. // appropriate state (started, starting). The dependency is marked as holding acquired; when
  652. // this service stops, the dependency will be released and may also stop.
  653. void start_dep(service_dep &dep)
  654. {
  655. if (! dep.holding_acq) {
  656. dep.get_to()->require();
  657. dep.holding_acq = true;
  658. }
  659. }
  660. };
  661. // Externally triggered service. This is essentially the same as an internal service, but does not start
  662. // until the external trigger is set.
  663. class triggered_service : public service_record {
  664. private:
  665. bool is_triggered = false;
  666. public:
  667. using service_record::service_record;
  668. bool bring_up() noexcept override;
  669. bool can_interrupt_start() noexcept override
  670. {
  671. return true;
  672. }
  673. void set_trigger(bool new_trigger) noexcept
  674. {
  675. is_triggered = new_trigger;
  676. if (is_triggered && get_state() == service_state_t::STARTING && !waiting_for_deps) {
  677. started();
  678. }
  679. }
  680. };
  681. inline auto extract_prop_queue(service_record *sr) -> decltype(sr->prop_queue_node) &
  682. {
  683. return sr->prop_queue_node;
  684. }
  685. inline auto extract_stop_queue(service_record *sr) -> decltype(sr->stop_queue_node) &
  686. {
  687. return sr->stop_queue_node;
  688. }
  689. inline auto extract_console_queue(service_record *sr) -> decltype(sr->console_queue_node) &
  690. {
  691. return sr->console_queue_node;
  692. }
  693. /*
  694. * A service_set, as the name suggests, manages a set of services.
  695. *
  696. * Other than the ability to find services by name, the service set manages various queues.
  697. * One is the queue for processes wishing to acquire the console. There is also a set of
  698. * processes that want to start, and another set of those that want to stop. These latter
  699. * two "queues" (not really queues since their order is not important) are used to prevent too
  700. * much recursion and to prevent service states from "bouncing" too rapidly.
  701. *
  702. * A service that wishes to start or stop puts itself on the start/stop queue; a service that
  703. * needs to propagate changes to dependent services or dependencies puts itself on the
  704. * propagation queue. Any operation that potentially manipulates the queues must be followed
  705. * by a "process queues" order (processQueues() method).
  706. *
  707. * Note that processQueues always repeatedly processes both queues until they are empty. The
  708. * process is finite because starting a service can never cause services to stop, unless they
  709. * fail to start, which should cause them to stop semi-permanently.
  710. */
  711. class service_set
  712. {
  713. protected:
  714. int active_services;
  715. std::list<service_record *> records;
  716. bool restart_enabled; // whether automatic restart is enabled (allowed)
  717. shutdown_type_t shutdown_type = shutdown_type_t::NONE; // Shutdown type, if stopping
  718. // Services waiting for exclusive access to the console
  719. dlist<service_record, extract_console_queue> console_queue;
  720. // Propagation and start/stop "queues" - list of services waiting for processing
  721. slist<service_record, extract_prop_queue> prop_queue;
  722. slist<service_record, extract_stop_queue> stop_queue;
  723. public:
  724. service_set() noexcept
  725. {
  726. active_services = 0;
  727. restart_enabled = true;
  728. }
  729. virtual ~service_set() noexcept
  730. {
  731. for (auto * s : records) {
  732. delete s;
  733. }
  734. }
  735. // Start the specified service. The service will be marked active.
  736. void start_service(service_record *svc) noexcept
  737. {
  738. svc->start();
  739. process_queues();
  740. }
  741. // Stop the specified service. Its active mark will be cleared.
  742. void stop_service(service_record *svc) noexcept
  743. {
  744. svc->stop(true);
  745. process_queues();
  746. }
  747. // Locate an existing service record.
  748. service_record *find_service(const std::string &name) noexcept;
  749. // Load a service description, and dependencies, if there is no existing
  750. // record for the given name.
  751. // Throws:
  752. // service_load_exc (or subclass) on problem with service description
  753. // std::bad_alloc on out-of-memory condition
  754. virtual service_record *load_service(const char *name)
  755. {
  756. auto r = find_service(name);
  757. if (r == nullptr) {
  758. throw service_not_found(name);
  759. }
  760. return r;
  761. }
  762. // Re-load a service description from file. If the service type changes then this returns
  763. // a new service instead (the old one should be removed and deleted by the caller).
  764. // Throws:
  765. // service_load_exc (or subclass) on problem with service description
  766. // std::bad_alloc on out-of-memory condition
  767. virtual service_record *reload_service(service_record *service)
  768. {
  769. return service;
  770. }
  771. // Start the service with the given name. The named service will begin
  772. // transition to the 'started' state.
  773. //
  774. // Throws a service_load_exc (or subclass) if the service description
  775. // cannot be loaded or is invalid;
  776. // Throws std::bad_alloc if out of memory.
  777. void start_service(const char *name)
  778. {
  779. using namespace std;
  780. service_record *record = load_service(name);
  781. service_set::start_service(record);
  782. }
  783. void add_service(service_record *svc)
  784. {
  785. records.push_back(svc);
  786. }
  787. void remove_service(service_record *svc) noexcept
  788. {
  789. records.erase(std::find(records.begin(), records.end(), svc));
  790. }
  791. void replace_service(service_record *orig, service_record *replacement) noexcept
  792. {
  793. auto i = std::find(records.begin(), records.end(), orig);
  794. *i = replacement;
  795. }
  796. // Get the list of all loaded services.
  797. const std::list<service_record *> &list_services() noexcept
  798. {
  799. return records;
  800. }
  801. // Add a service record to the state propagation queue. The service record will have its
  802. // do_propagation() method called when the queue is processed.
  803. void add_prop_queue(service_record *service) noexcept
  804. {
  805. if (! prop_queue.is_queued(service)) {
  806. prop_queue.insert(service);
  807. }
  808. }
  809. // Add a service record to the stop queue. The service record will have its
  810. // execute_transition() method called when the queue is processed.
  811. void add_transition_queue(service_record *service) noexcept
  812. {
  813. if (! stop_queue.is_queued(service)) {
  814. stop_queue.insert(service);
  815. }
  816. }
  817. // Process state propagation and start/stop queues, until they are empty.
  818. void process_queues() noexcept
  819. {
  820. while (! stop_queue.is_empty() || ! prop_queue.is_empty()) {
  821. while (! prop_queue.is_empty()) {
  822. auto next = prop_queue.pop_front();
  823. next->do_propagation();
  824. }
  825. if (! stop_queue.is_empty()) {
  826. auto next = stop_queue.pop_front();
  827. next->execute_transition();
  828. }
  829. }
  830. }
  831. // Set the console queue tail (returns previous tail)
  832. void append_console_queue(service_record * newTail) noexcept
  833. {
  834. bool was_empty = console_queue.is_empty();
  835. console_queue.append(newTail);
  836. if (was_empty) {
  837. enable_console_log(false);
  838. }
  839. }
  840. // Pull and dispatch a waiter from the console queue
  841. void pull_console_queue() noexcept
  842. {
  843. if (console_queue.is_empty()) {
  844. // Discard the log buffer now, because we've potentially blocked output for a while
  845. // and allowed it to fill with stale messages. (If not much time has passed, the
  846. // request to discard will be ignored anyway).
  847. discard_console_log_buffer();
  848. enable_console_log(true);
  849. }
  850. else {
  851. service_record * front = console_queue.pop_front();
  852. front->acquired_console();
  853. }
  854. }
  855. void unqueue_console(service_record * service) noexcept
  856. {
  857. if (console_queue.is_queued(service)) {
  858. console_queue.unlink(service);
  859. }
  860. }
  861. // Check if console queue is empty (possibly due to console already having
  862. // been assigned to the only queueing service)
  863. bool is_console_queue_empty() noexcept
  864. {
  865. return console_queue.is_empty();
  866. }
  867. // Check whether a service is queued for the console
  868. bool is_queued_for_console(service_record * service) noexcept
  869. {
  870. return console_queue.is_queued(service);
  871. }
  872. // Notification from service that it is active (state != STOPPED)
  873. // Only to be called on the transition from inactive to active.
  874. void service_active(service_record *) noexcept;
  875. // Notification from service that it is inactive (STOPPED)
  876. // Only to be called on the transition from active to inactive.
  877. void service_inactive(service_record *) noexcept;
  878. // Find out how many services are active (starting, running or stopping,
  879. // but not stopped).
  880. int count_active_services() noexcept
  881. {
  882. return active_services;
  883. }
  884. void stop_all_services(shutdown_type_t type = shutdown_type_t::HALT) noexcept
  885. {
  886. restart_enabled = false;
  887. shutdown_type = type;
  888. for (std::list<service_record *>::iterator i = records.begin(); i != records.end(); ++i) {
  889. (*i)->stop(false);
  890. (*i)->unpin();
  891. }
  892. process_queues();
  893. }
  894. bool is_shutting_down() noexcept
  895. {
  896. return !restart_enabled;
  897. }
  898. shutdown_type_t get_shutdown_type() noexcept
  899. {
  900. return shutdown_type;
  901. }
  902. // Get an identifier for the run-time type of the service set (similar to typeid, but without
  903. // requiring RTTI to be enabled during compilation).
  904. virtual int get_set_type_id() noexcept
  905. {
  906. return SSET_TYPE_NONE;
  907. }
  908. };
  909. // A service set which loads services from one of several service directories.
  910. class dirload_service_set : public service_set
  911. {
  912. service_dir_pathlist service_dirs;
  913. // Implementation of service load/reload.
  914. // Find a service record, or load it from file. If the service has dependencies, load those also.
  915. //
  916. // If reload_svc != nullptr, then reload the specified service (with name specified by name). The return
  917. // points to the new service, which may be a new service record, in which case the caller must remove
  918. // the original record.
  919. //
  920. // If avoid_circular != nullptr (but reload_svc == nullptr), and if the service name refers to the
  921. // service referred to by avoid_circular, a circular dependency is recognised. (A circular dependency
  922. // is otherwise recognised on services as they are loading; this mechanism should be used when
  923. // reloading a service, to prevent new dependencies forming on the original service).
  924. //
  925. // Throws service_load_exc (or subclass) if a dependency cycle is found or if another
  926. // problem occurs (I/O error, service description not found etc). Throws std::bad_alloc
  927. // if a memory allocation failure occurs.
  928. //
  929. service_record *load_reload_service(const char *name, service_record *reload_svc,
  930. const service_record *avoid_circular);
  931. public:
  932. dirload_service_set() noexcept : service_set()
  933. {
  934. // nothing to do.
  935. }
  936. dirload_service_set(service_dir_pathlist &&pathlist) noexcept : service_set(), service_dirs(std::move(pathlist))
  937. {
  938. // nothing to do.
  939. }
  940. dirload_service_set(const char *path, bool dyn_alloc = false)
  941. {
  942. service_dirs.emplace_back(path, dyn_alloc);
  943. }
  944. dirload_service_set(const dirload_service_set &) = delete;
  945. int get_service_dir_count() noexcept
  946. {
  947. return service_dirs.size();
  948. }
  949. const char * get_service_dir(int n) noexcept
  950. {
  951. return service_dirs[n].get_dir();
  952. }
  953. service_record *load_service(const char *name) override
  954. {
  955. return load_service(name, nullptr);
  956. }
  957. service_record *load_service(const char *name, const service_record *avoid_circular);
  958. service_record *reload_service(service_record *service) override;
  959. int get_set_type_id() noexcept override
  960. {
  961. return SSET_TYPE_DIRLOAD;
  962. }
  963. };
  964. #endif