load-service.cc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. #include <algorithm>
  2. #include <string>
  3. #include <fstream>
  4. #include <locale>
  5. #include <limits>
  6. #include <list>
  7. #include <cstring>
  8. #include <cstdlib>
  9. #include <sys/stat.h>
  10. #include <sys/types.h>
  11. #include <pwd.h>
  12. #include <grp.h>
  13. #include <dirent.h>
  14. #include "proc-service.h"
  15. #include "dinit-log.h"
  16. #include "dinit-util.h"
  17. #include "dinit-utmp.h"
  18. using string = std::string;
  19. using string_iterator = std::string::iterator;
  20. // Perform environment variable substitution on a command line, if specified.
  21. // line - the string storing the command and arguments
  22. // offsets - the [start,end) pair of offsets of the command and each argument within the string
  23. //
  24. static void do_env_subst(const char *setting_name, std::string &line,
  25. std::list<std::pair<unsigned,unsigned>> &offsets, bool do_sub_vars)
  26. {
  27. using namespace dinit_load;
  28. if (do_sub_vars) {
  29. cmdline_var_subst(setting_name, line, offsets, resolve_env_var);
  30. }
  31. }
  32. // Process a dependency directory - filenames contained within correspond to service names which
  33. // are loaded and added as a dependency of the given type. Expected use is with a directory
  34. // containing symbolic links to other service descriptions, but this isn't required.
  35. // Failure to read the directory contents, or to find a service listed within, is not considered
  36. // a fatal error.
  37. static void process_dep_dir(dirload_service_set &sset,
  38. const char *servicename,
  39. const string &service_filename,
  40. std::list<prelim_dep> &deplist, const std::string &depdirpath,
  41. dependency_type dep_type,
  42. const service_record *avoid_circular)
  43. {
  44. std::string depdir_fname = combine_paths(parent_path(service_filename), depdirpath.c_str());
  45. DIR *depdir = opendir(depdir_fname.c_str());
  46. if (depdir == nullptr) {
  47. log(loglevel_t::WARN, "Could not open dependency directory '", depdir_fname,
  48. "' for ", servicename, " service.");
  49. return;
  50. }
  51. errno = 0;
  52. dirent * dent = readdir(depdir);
  53. while (dent != nullptr) {
  54. char * name = dent->d_name;
  55. if (name[0] != '.') {
  56. try {
  57. service_record * sr = sset.load_service(name);
  58. deplist.emplace_back(sr, dep_type);
  59. }
  60. catch (service_not_found &) {
  61. log(loglevel_t::WARN, "Ignoring unresolved dependency '", name,
  62. "' in dependency directory '", depdirpath,
  63. "' for ", servicename, " service.");
  64. }
  65. }
  66. dent = readdir(depdir);
  67. }
  68. if (errno != 0) {
  69. log(loglevel_t::WARN, "Error reading dependency directory '", depdirpath,
  70. "' for ", servicename, " service.");
  71. }
  72. closedir(depdir);
  73. }
  74. service_record * dirload_service_set::load_service(const char * name, const service_record *avoid_circular)
  75. {
  76. return load_reload_service(name, nullptr, avoid_circular);
  77. }
  78. service_record * dirload_service_set::reload_service(service_record * service)
  79. {
  80. return load_reload_service(service->get_name().c_str(), service, service);
  81. }
  82. // Update the dependencies of the specified service atomically. May fail with bad_alloc.
  83. static void update_depenencies(service_record *service,
  84. dinit_load::service_settings_wrapper<prelim_dep> &settings)
  85. {
  86. std::list<service_dep> &deps = service->get_dependencies();
  87. auto first_preexisting = deps.begin();
  88. // build a set of services currently issuing acquisition
  89. std::unordered_set<service_record *> deps_with_acqs;
  90. for (auto i = deps.begin(), e = deps.end(); i != e; ++i) {
  91. if (i->holding_acq) {
  92. deps_with_acqs.insert(i->get_to());
  93. }
  94. }
  95. try {
  96. // Insert all the new dependencies before the first pre-existing dependency
  97. for (auto &new_dep : settings.depends) {
  98. bool has_acq = deps_with_acqs.count(new_dep.to);
  99. service->add_dep(new_dep.to, new_dep.dep_type, first_preexisting, has_acq);
  100. }
  101. }
  102. catch (...) {
  103. // remove the inserted dependencies
  104. for (auto i = deps.begin(); i != first_preexisting; ++i) {
  105. i = service->rm_dep(i);
  106. }
  107. // re-throw the exception
  108. throw;
  109. }
  110. // Now remove all pre-existing dependencies (no exceptions possible from here).
  111. for( ; first_preexisting != deps.end(); ) {
  112. first_preexisting = service->rm_dep(first_preexisting);
  113. }
  114. }
  115. // Update the command, and dependencies, of the specified service atomically. May fail with bad_alloc.
  116. static void update_command_and_dependencies(base_process_service *service,
  117. dinit_load::service_settings_wrapper<prelim_dep> &settings)
  118. {
  119. // Get the current command parts
  120. std::string orig_cmd; std::vector<const char *> orig_arg_parts;
  121. service->get_command(orig_cmd, orig_arg_parts);
  122. // Separate the new command parts and set
  123. std::vector<const char *> cmd_arg_parts = separate_args(settings.command, settings.command_offsets);
  124. service->set_command(std::move(settings.command), std::move(cmd_arg_parts));
  125. try {
  126. update_depenencies(service, settings);
  127. }
  128. catch (...) {
  129. // restore original command
  130. service->set_command(std::move(orig_cmd), std::move(orig_arg_parts));
  131. // re-throw the exception
  132. throw;
  133. }
  134. }
  135. service_record * dirload_service_set::load_reload_service(const char *name, service_record *reload_svc,
  136. const service_record *avoid_circular)
  137. {
  138. // For reload, we have the following problems:
  139. // - ideally want to allow changing service type, at least for stopped services. That implies creating
  140. // a new (replacement) service_record object, at least in cases where the type does change.
  141. // - dependencies may change (including addition of new dependencies which aren't yet loaded). We need
  142. // to prevent cyclic dependencies forming.
  143. // - We want atomicity. If any new settings are not valid/alterable, or if a cyclic dependency is
  144. // created, nothing should change. Ideally this would extend to unloading any dependencies which were
  145. // loaded as part of the reload attempt.
  146. // - We need to either transfer handles referring to the old service (so that they refer to the new
  147. // service), or make them invalid. Or, we alter the original service without creating a new one
  148. // (which we can only do if the type doesn't change).
  149. // Approach:
  150. // - remember the initial service count, so we can remove services loaded as part of the reload
  151. // operation if we want to abort it later (i.e. if service count changed from N to N+X, remove the
  152. // last X services)
  153. // - check that the new settings are valid (if the service is running, check if the settings can be
  154. // altered, though we may just defer some changes until service is restarted)
  155. // - check all dependencies of the newly created service record for cyclic dependencies, via depth-first
  156. // traversal.
  157. // - If changing type:
  158. // - create the service initially just as if loading a new service (but with no dummy placeholder,
  159. // use the original service for that).
  160. // - switch all dependents to depend on the new record. Copy necessary runtime data from the original
  161. // to the new service record. Remove dependencies from the old record, and release any dependency
  162. // services as appropriate (so they stop if no longer needed). Finally, remove the old service
  163. // record and delete it.
  164. // Otherwise:
  165. // - copy the new settings to the existing service
  166. // - fix dependencies
  167. //
  168. // Limitations:
  169. // - caller must check there are no handles (or only a single requesting handle) to the service before
  170. // calling
  171. // - cannot change the type of a non-stopped service
  172. using std::string;
  173. using std::ifstream;
  174. using std::ios;
  175. using std::ios_base;
  176. using std::locale;
  177. using std::isspace;
  178. using std::list;
  179. using std::pair;
  180. using namespace dinit_load;
  181. if (reload_svc == nullptr) {
  182. // First try and find an existing record...
  183. service_record * rval = find_service(string(name));
  184. if (rval != nullptr) {
  185. if (rval == avoid_circular || rval->is_dummy()) {
  186. throw service_cyclic_dependency(name);
  187. }
  188. return rval;
  189. }
  190. }
  191. service_record *rval = nullptr;
  192. service_record *dummy = nullptr;
  193. ifstream service_file;
  194. string service_filename;
  195. int fail_load_errno = 0;
  196. std::string fail_load_path;
  197. // Couldn't find one. Have to load it.
  198. for (auto &service_dir : service_dirs) {
  199. service_filename = service_dir.get_dir();
  200. if (*(service_filename.rbegin()) != '/') {
  201. service_filename += '/';
  202. }
  203. service_filename += name;
  204. service_file.open(service_filename.c_str(), ios::in);
  205. if (service_file) break;
  206. if (errno != ENOENT && fail_load_errno == 0) {
  207. fail_load_errno = errno;
  208. fail_load_path = std::move(service_filename);
  209. }
  210. }
  211. if (!service_file) {
  212. if (fail_load_errno == 0) {
  213. throw service_not_found(string(name));
  214. }
  215. else {
  216. throw service_load_error(name, std::move(fail_load_path), fail_load_errno);
  217. }
  218. }
  219. service_settings_wrapper<prelim_dep> settings;
  220. string line;
  221. // getline can set failbit if it reaches end-of-file, we don't want an exception in that case. There's
  222. // no good way to handle an I/O error however, so we'll have exceptions thrown on badbit:
  223. service_file.exceptions(ios::badbit);
  224. bool create_new_record = true;
  225. try {
  226. if (reload_svc == nullptr) {
  227. // Add a dummy service record now to prevent infinite recursion in case of cyclic dependency.
  228. // We replace this with the real service later (or remove it if we find a configuration error).
  229. dummy = new service_record(this, string(name));
  230. add_service(dummy);
  231. }
  232. process_service_file(name, service_file,
  233. [&](string &line, unsigned line_num, string &setting,
  234. string_iterator &i, string_iterator &end) -> void {
  235. auto process_dep_dir_n = [&](std::list<prelim_dep> &deplist, const std::string &waitsford,
  236. dependency_type dep_type) -> void {
  237. process_dep_dir(*this, name, service_filename, deplist, waitsford, dep_type, reload_svc);
  238. };
  239. auto load_service_n = [&](const string &dep_name) -> service_record * {
  240. return load_service(dep_name.c_str(), reload_svc);
  241. };
  242. process_service_line(settings, name, line, line_num, setting, i, end, load_service_n,
  243. process_dep_dir_n);
  244. });
  245. service_file.close();
  246. auto report_err = [&](const char *msg){
  247. throw service_load_exc(name, msg);
  248. };
  249. settings.finalise(report_err);
  250. auto service_type = settings.service_type;
  251. if (reload_svc != nullptr) {
  252. // Make sure settings are able to be changed/are compatible
  253. service_record *service = reload_svc;
  254. if (service->get_state() != service_state_t::STOPPED) {
  255. // Can not change type of a running service.
  256. if (service_type != service->get_type()) {
  257. throw service_load_exc(name, "cannot change type of non-stopped service.");
  258. }
  259. // Can not alter a starting/stopping service, at least for now.
  260. if (service->get_state() != service_state_t::STARTED) {
  261. throw service_load_exc(name,
  262. "cannot alter settings for service which is currently starting/stopping.");
  263. }
  264. // Check validity of dependencies (if started, regular deps must be started)
  265. for (auto &new_dep : settings.depends) {
  266. if (new_dep.dep_type == dependency_type::REGULAR) {
  267. if (new_dep.to->get_state() != service_state_t::STARTED) {
  268. throw service_load_exc(name,
  269. std::string("cannot add non-started dependency '")
  270. + new_dep.to->get_name() + "'.");
  271. }
  272. }
  273. }
  274. // Cannot change certain flags
  275. auto current_flags = service->get_flags();
  276. if (current_flags.starts_on_console != settings.onstart_flags.starts_on_console
  277. || current_flags.shares_console != settings.onstart_flags.shares_console) {
  278. throw service_load_exc(name, "cannot change starts_on_console/"
  279. "shares_console flags for a running service.");
  280. }
  281. // Cannot change pid file
  282. if (service->get_type() == service_type_t::BGPROCESS) {
  283. auto *bgp_service = static_cast<bgproc_service *>(service);
  284. if (bgp_service->get_pid_file() != settings.pid_file) {
  285. throw service_load_exc(name, "cannot change pid_file for running service.");
  286. }
  287. }
  288. // Cannot change inittab_id/inittab_line
  289. #if USE_UTMPX
  290. if (service->get_type() == service_type_t::PROCESS) {
  291. auto *proc_service = static_cast<process_service *>(service);
  292. auto *svc_utmp_id = proc_service->get_utmp_id();
  293. auto *svc_utmp_ln = proc_service->get_utmp_line();
  294. if (strncmp(svc_utmp_id, settings.inittab_id, proc_service->get_utmp_id_size()) != 0
  295. || strncmp(svc_utmp_ln, settings.inittab_line,
  296. proc_service->get_utmp_line_size()) != 0) {
  297. throw service_load_exc(name, "cannot change inittab-id or inittab-line "
  298. "settings for running service.");
  299. }
  300. }
  301. #endif
  302. // Already started; we must replace settings on existing service record
  303. create_new_record = false;
  304. }
  305. }
  306. // Note, we need to be very careful to handle exceptions properly and roll back any changes that
  307. // we've made before the exception occurred.
  308. if (service_type == service_type_t::PROCESS) {
  309. do_env_subst("command", settings.command, settings.command_offsets, settings.do_sub_vars);
  310. do_env_subst("stop-command", settings.stop_command, settings.stop_command_offsets, settings.do_sub_vars);
  311. std::vector<const char *> stop_arg_parts = separate_args(settings.stop_command, settings.stop_command_offsets);
  312. process_service *rvalps;
  313. if (create_new_record) {
  314. rvalps = new process_service(this, string(name), std::move(settings.command),
  315. settings.command_offsets, settings.depends);
  316. }
  317. else {
  318. rvalps = static_cast<process_service *>(reload_svc);
  319. update_command_and_dependencies(rvalps, settings);
  320. }
  321. rval = rvalps;
  322. // All of the following should be noexcept or must perform rollback on exception
  323. rvalps->set_stop_command(std::move(settings.stop_command), std::move(stop_arg_parts));
  324. rvalps->set_working_dir(std::move(settings.working_dir));
  325. rvalps->set_env_file(std::move(settings.env_file));
  326. #if SUPPORT_CGROUPS
  327. rvalps->set_cgroup(std::move(settings.run_in_cgroup));
  328. #endif
  329. rvalps->set_rlimits(std::move(settings.rlimits));
  330. rvalps->set_restart_interval(settings.restart_interval, settings.max_restarts);
  331. rvalps->set_restart_delay(settings.restart_delay);
  332. rvalps->set_stop_timeout(settings.stop_timeout);
  333. rvalps->set_start_timeout(settings.start_timeout);
  334. rvalps->set_extra_termination_signal(settings.term_signal);
  335. rvalps->set_run_as_uid_gid(settings.run_as_uid, settings.run_as_gid);
  336. rvalps->set_notification_fd(settings.readiness_fd);
  337. rvalps->set_notification_var(std::move(settings.readiness_var));
  338. #if USE_UTMPX
  339. rvalps->set_utmp_id(settings.inittab_id);
  340. rvalps->set_utmp_line(settings.inittab_line);
  341. #endif
  342. }
  343. else if (service_type == service_type_t::BGPROCESS) {
  344. do_env_subst("command", settings.command, settings.command_offsets, settings.do_sub_vars);
  345. do_env_subst("stop-command", settings.stop_command, settings.stop_command_offsets, settings.do_sub_vars);
  346. std::vector<const char *> stop_arg_parts = separate_args(settings.stop_command, settings.stop_command_offsets);
  347. bgproc_service *rvalps;
  348. if (create_new_record) {
  349. rvalps = new bgproc_service(this, string(name), std::move(settings.command),
  350. settings.command_offsets, settings.depends);
  351. }
  352. else {
  353. rvalps = static_cast<bgproc_service *>(reload_svc);
  354. update_command_and_dependencies(rvalps, settings);
  355. }
  356. rval = rvalps;
  357. // All of the following should be noexcept or must perform rollback on exception
  358. rvalps->set_stop_command(std::move(settings.stop_command), std::move(stop_arg_parts));
  359. rvalps->set_working_dir(std::move(settings.working_dir));
  360. rvalps->set_env_file(std::move(settings.env_file));
  361. #if SUPPORT_CGROUPS
  362. rvalps->set_cgroup(std::move(settings.run_in_cgroup));
  363. #endif
  364. rvalps->set_rlimits(std::move(settings.rlimits));
  365. rvalps->set_pid_file(std::move(settings.pid_file));
  366. rvalps->set_restart_interval(settings.restart_interval, settings.max_restarts);
  367. rvalps->set_restart_delay(settings.restart_delay);
  368. rvalps->set_stop_timeout(settings.stop_timeout);
  369. rvalps->set_start_timeout(settings.start_timeout);
  370. rvalps->set_extra_termination_signal(settings.term_signal);
  371. rvalps->set_run_as_uid_gid(settings.run_as_uid, settings.run_as_gid);
  372. settings.onstart_flags.runs_on_console = false;
  373. }
  374. else if (service_type == service_type_t::SCRIPTED) {
  375. do_env_subst("command", settings.command, settings.command_offsets, settings.do_sub_vars);
  376. do_env_subst("stop-command", settings.stop_command, settings.stop_command_offsets, settings.do_sub_vars);
  377. std::vector<const char *> stop_arg_parts = separate_args(settings.stop_command, settings.stop_command_offsets);
  378. scripted_service *rvalps;
  379. if (create_new_record) {
  380. rvalps = new scripted_service(this, string(name), std::move(settings.command),
  381. settings.command_offsets, settings.depends);
  382. }
  383. else {
  384. rvalps = static_cast<scripted_service *>(reload_svc);
  385. update_command_and_dependencies(rvalps, settings);
  386. }
  387. rval = rvalps;
  388. // All of the following should be noexcept or must perform rollback on exception
  389. rvalps->set_stop_command(std::move(settings.stop_command), std::move(stop_arg_parts));
  390. rvalps->set_working_dir(std::move(settings.working_dir));
  391. rvalps->set_env_file(std::move(settings.env_file));
  392. #if SUPPORT_CGROUPS
  393. rvalps->set_cgroup(std::move(settings.run_in_cgroup));
  394. #endif
  395. rvalps->set_rlimits(std::move(settings.rlimits));
  396. rvalps->set_stop_timeout(settings.stop_timeout);
  397. rvalps->set_start_timeout(settings.start_timeout);
  398. rvalps->set_extra_termination_signal(settings.term_signal);
  399. rvalps->set_run_as_uid_gid(settings.run_as_uid, settings.run_as_gid);
  400. }
  401. else {
  402. if (create_new_record) {
  403. rval = new service_record(this, string(name), service_type, settings.depends);
  404. }
  405. else {
  406. rval = reload_svc;
  407. update_depenencies(rval, settings);
  408. }
  409. }
  410. rval->set_log_file(std::move(settings.logfile));
  411. rval->set_auto_restart(settings.auto_restart);
  412. rval->set_smooth_recovery(settings.smooth_recovery);
  413. rval->set_flags(settings.onstart_flags);
  414. rval->set_socket_details(std::move(settings.socket_path), settings.socket_perms,
  415. settings.socket_uid, settings.socket_gid);
  416. rval->set_chain_to(std::move(settings.chain_to_name));
  417. if (create_new_record && reload_svc != nullptr) {
  418. // switch dependencies on old record so that they refer to the new record
  419. // Add dependent-link for all dependencies. Add to the new service first, so we can rollback
  420. // on failure:
  421. int added_dep_links = 0;
  422. try {
  423. for (auto &dep : rval->get_dependencies()) {
  424. dep.get_to()->get_dependents().push_back(&dep);
  425. added_dep_links++;
  426. }
  427. }
  428. catch (...) {
  429. for (auto &dep : rval->get_dependencies()) {
  430. if (added_dep_links-- == 0) break;
  431. dep.get_to()->get_dependents().pop_back();
  432. }
  433. throw;
  434. }
  435. // Remove dependent-link for all dependencies from the original:
  436. reload_svc->prepare_for_unload();
  437. // Set links in all dependents to the original to point to the new service:
  438. rval->get_dependents() = std::move(reload_svc->get_dependents());
  439. for (auto n : rval->get_dependents()) {
  440. n->set_to(rval);
  441. }
  442. }
  443. if (dummy != nullptr) {
  444. auto iter = std::find(records.begin(), records.end(), dummy);
  445. *iter = rval;
  446. delete dummy;
  447. }
  448. return rval;
  449. }
  450. catch (setting_exception &setting_exc)
  451. {
  452. // Must remove the dummy service record.
  453. if (dummy != nullptr) {
  454. records.erase(std::find(records.begin(), records.end(), dummy));
  455. delete dummy;
  456. }
  457. if (create_new_record) delete rval;
  458. if (setting_exc.line_num != (unsigned)-1) {
  459. throw service_description_exc(name, std::move(setting_exc.get_info()), setting_exc.line_num);
  460. }
  461. else {
  462. throw service_description_exc(name, std::move(setting_exc.get_info()), setting_exc.setting_name);
  463. }
  464. }
  465. catch (std::system_error &sys_err)
  466. {
  467. if (dummy != nullptr) {
  468. records.erase(std::find(records.begin(), records.end(), dummy));
  469. delete dummy;
  470. }
  471. if (create_new_record) delete rval;
  472. throw service_load_exc(name, sys_err.what());
  473. }
  474. catch (...) // (should only be std::bad_alloc / service_description_exc)
  475. {
  476. if (dummy != nullptr) {
  477. records.erase(std::find(records.begin(), records.end(), dummy));
  478. delete dummy;
  479. }
  480. if (create_new_record) delete rval;
  481. throw;
  482. }
  483. }