runsvdir.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. /*
  2. Copyright (c) 2001-2006, Gerrit Pape
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. 1. Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. 2. Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. 3. The name of the author may not be used to endorse or promote products
  12. derived from this software without specific prior written permission.
  13. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
  14. WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  15. MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  16. EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  17. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  18. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  19. OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  20. WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  21. OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  22. ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. */
  24. /* Busyboxed by Denys Vlasenko <vda.linux@googlemail.com> */
  25. //config:config RUNSVDIR
  26. //config: bool "runsvdir (6 kb)"
  27. //config: default y
  28. //config: help
  29. //config: runsvdir starts a runsv process for each subdirectory, or symlink to
  30. //config: a directory, in the services directory dir, up to a limit of 1000
  31. //config: subdirectories, and restarts a runsv process if it terminates.
  32. //config:
  33. //config:config FEATURE_RUNSVDIR_LOG
  34. //config: bool "Enable scrolling argument log"
  35. //config: depends on RUNSVDIR
  36. //config: default n
  37. //config: help
  38. //config: Enable feature where second parameter of runsvdir holds last error
  39. //config: message (viewable via top/ps). Otherwise (feature is off
  40. //config: or no parameter), error messages go to stderr only.
  41. //applet:IF_RUNSVDIR(APPLET(runsvdir, BB_DIR_USR_BIN, BB_SUID_DROP))
  42. //kbuild:lib-$(CONFIG_RUNSVDIR) += runsvdir.o
  43. //usage:#define runsvdir_trivial_usage
  44. //usage: "[-P] [-s SCRIPT] DIR"
  45. //usage:#define runsvdir_full_usage "\n\n"
  46. //usage: "Start a runsv process for each subdirectory. If it exits, restart it.\n"
  47. //usage: "\n -P Put each runsv in a new session"
  48. //usage: "\n -s SCRIPT Run SCRIPT <signo> after signal is processed"
  49. #include <sys/file.h>
  50. #include "libbb.h"
  51. #include "common_bufsiz.h"
  52. #include "runit_lib.h"
  53. #define MAXSERVICES 1000
  54. /* Should be not needed - all dirs are on same FS, right? */
  55. #define CHECK_DEVNO_TOO 0
  56. struct service {
  57. #if CHECK_DEVNO_TOO
  58. dev_t dev;
  59. #endif
  60. ino_t ino;
  61. pid_t pid;
  62. smallint isgone;
  63. };
  64. struct globals {
  65. struct service *sv;
  66. char *svdir;
  67. int svnum;
  68. #if ENABLE_FEATURE_RUNSVDIR_LOG
  69. char *rplog;
  70. struct fd_pair logpipe;
  71. struct pollfd pfd[1];
  72. unsigned stamplog;
  73. #endif
  74. } FIX_ALIASING;
  75. #define G (*(struct globals*)bb_common_bufsiz1)
  76. #define sv (G.sv )
  77. #define svdir (G.svdir )
  78. #define svnum (G.svnum )
  79. #define rplog (G.rplog )
  80. #define logpipe (G.logpipe )
  81. #define pfd (G.pfd )
  82. #define stamplog (G.stamplog )
  83. #define INIT_G() do { setup_common_bufsiz(); } while (0)
  84. static void fatal2_cannot(const char *m1, const char *m2)
  85. {
  86. bb_perror_msg_and_die("%s: fatal: can't %s%s", svdir, m1, m2);
  87. /* was exiting 100 */
  88. }
  89. static void warn3x(const char *m1, const char *m2, const char *m3)
  90. {
  91. bb_error_msg("%s: warning: %s%s%s", svdir, m1, m2, m3);
  92. }
  93. static void warn2_cannot(const char *m1, const char *m2)
  94. {
  95. warn3x("can't ", m1, m2);
  96. }
  97. #if ENABLE_FEATURE_RUNSVDIR_LOG
  98. static void warnx(const char *m1)
  99. {
  100. warn3x(m1, "", "");
  101. }
  102. #endif
  103. /* inlining + vfork -> bigger code */
  104. static NOINLINE pid_t runsv(const char *name)
  105. {
  106. pid_t pid;
  107. /* If we got signaled, stop spawning children at once! */
  108. if (bb_got_signal)
  109. return 0;
  110. pid = vfork();
  111. if (pid == -1) {
  112. warn2_cannot("vfork", "");
  113. return 0;
  114. }
  115. if (pid == 0) {
  116. /* child */
  117. if (option_mask32 & 1) /* -P option? */
  118. setsid();
  119. /* man execv:
  120. * "Signals set to be caught by the calling process image
  121. * shall be set to the default action in the new process image."
  122. * Therefore, we do not need this: */
  123. #if 0
  124. bb_signals(0
  125. | (1 << SIGHUP)
  126. | (1 << SIGTERM)
  127. , SIG_DFL);
  128. #endif
  129. execlp("runsv", "runsv", name, (char *) NULL);
  130. fatal2_cannot("start runsv ", name);
  131. }
  132. return pid;
  133. }
  134. /* gcc 4.3.0 does better with NOINLINE */
  135. static NOINLINE int do_rescan(void)
  136. {
  137. DIR *dir;
  138. struct dirent *d;
  139. int i;
  140. struct stat s;
  141. int need_rescan = 0;
  142. dir = opendir(".");
  143. if (!dir) {
  144. warn2_cannot("open directory ", svdir);
  145. return 1; /* need to rescan again soon */
  146. }
  147. for (i = 0; i < svnum; i++)
  148. sv[i].isgone = 1;
  149. while (1) {
  150. errno = 0;
  151. d = readdir(dir);
  152. if (!d)
  153. break;
  154. if (d->d_name[0] == '.')
  155. continue;
  156. if (stat(d->d_name, &s) == -1) {
  157. warn2_cannot("stat ", d->d_name);
  158. continue;
  159. }
  160. if (!S_ISDIR(s.st_mode))
  161. continue;
  162. /* Do we have this service listed already? */
  163. for (i = 0; i < svnum; i++) {
  164. if (sv[i].ino == s.st_ino
  165. #if CHECK_DEVNO_TOO
  166. && sv[i].dev == s.st_dev
  167. #endif
  168. ) {
  169. if (sv[i].pid == 0) /* restart if it has died */
  170. goto run_ith_sv;
  171. sv[i].isgone = 0; /* "we still see you" */
  172. goto next_dentry;
  173. }
  174. }
  175. { /* Not found, make new service */
  176. struct service *svnew = realloc(sv, (i+1) * sizeof(*sv));
  177. if (!svnew) {
  178. warn2_cannot("start runsv ", d->d_name);
  179. need_rescan = 1;
  180. continue;
  181. }
  182. sv = svnew;
  183. svnum++;
  184. #if CHECK_DEVNO_TOO
  185. sv[i].dev = s.st_dev;
  186. #endif
  187. sv[i].ino = s.st_ino;
  188. run_ith_sv:
  189. sv[i].pid = runsv(d->d_name);
  190. sv[i].isgone = 0;
  191. }
  192. next_dentry: ;
  193. }
  194. i = errno;
  195. closedir(dir);
  196. if (i) { /* readdir failed */
  197. warn2_cannot("read directory ", svdir);
  198. return 1; /* need to rescan again soon */
  199. }
  200. /* Send SIGTERM to runsv whose directories
  201. * were no longer found (-> must have been removed) */
  202. for (i = 0; i < svnum; i++) {
  203. if (!sv[i].isgone)
  204. continue;
  205. if (sv[i].pid)
  206. kill(sv[i].pid, SIGTERM);
  207. svnum--;
  208. sv[i] = sv[svnum];
  209. i--; /* so that we don't skip new sv[i] (bug was here!) */
  210. }
  211. return need_rescan;
  212. }
  213. int runsvdir_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  214. int runsvdir_main(int argc UNUSED_PARAM, char **argv)
  215. {
  216. struct stat s;
  217. dev_t last_dev = last_dev; /* for gcc */
  218. ino_t last_ino = last_ino; /* for gcc */
  219. time_t last_mtime;
  220. int curdir;
  221. unsigned stampcheck;
  222. int i;
  223. int need_rescan;
  224. bool i_am_init;
  225. char *opt_s_argv[3];
  226. INIT_G();
  227. opt_s_argv[0] = NULL;
  228. opt_s_argv[2] = NULL;
  229. getopt32(argv, "^" "Ps:" "\0" "-1", &opt_s_argv[0]);
  230. argv += optind;
  231. i_am_init = (getpid() == 1);
  232. bb_signals(0
  233. | (1 << SIGTERM)
  234. | (1 << SIGHUP)
  235. /* For busybox's init, SIGTERM == reboot,
  236. * SIGUSR1 == halt,
  237. * SIGUSR2 == poweroff,
  238. * Ctlr-ALt-Del sends SIGINT to init,
  239. * so we need to intercept SIGUSRn and SIGINT too.
  240. * Note that we do not implement actual reboot
  241. * (killall(TERM) + umount, etc), we just pause
  242. * respawing and avoid exiting (-> making kernel oops).
  243. * The user is responsible for the rest.
  244. */
  245. | (i_am_init ? ((1 << SIGUSR1) | (1 << SIGUSR2) | (1 << SIGINT)) : 0)
  246. , record_signo);
  247. svdir = *argv++;
  248. #if ENABLE_FEATURE_RUNSVDIR_LOG
  249. /* setup log */
  250. if (*argv) {
  251. rplog = *argv;
  252. if (strlen(rplog) < 7) {
  253. warnx("log must have at least seven characters");
  254. } else if (piped_pair(logpipe)) {
  255. warnx("can't create pipe for log");
  256. } else {
  257. close_on_exec_on(logpipe.rd);
  258. close_on_exec_on(logpipe.wr);
  259. ndelay_on(logpipe.rd);
  260. ndelay_on(logpipe.wr);
  261. if (dup2(logpipe.wr, 2) == -1) {
  262. warnx("can't set filedescriptor for log");
  263. } else {
  264. pfd[0].fd = logpipe.rd;
  265. pfd[0].events = POLLIN;
  266. stamplog = monotonic_sec();
  267. goto run;
  268. }
  269. }
  270. rplog = NULL;
  271. warnx("log service disabled");
  272. }
  273. run:
  274. #endif
  275. curdir = open(".", O_RDONLY|O_NDELAY);
  276. if (curdir == -1)
  277. fatal2_cannot("open current directory", "");
  278. close_on_exec_on(curdir);
  279. stampcheck = monotonic_sec();
  280. need_rescan = 1;
  281. last_mtime = 0;
  282. for (;;) {
  283. unsigned now;
  284. unsigned sig;
  285. /* collect children */
  286. for (;;) {
  287. pid_t pid = wait_any_nohang(NULL);
  288. if (pid <= 0)
  289. break;
  290. for (i = 0; i < svnum; i++) {
  291. if (pid == sv[i].pid) {
  292. /* runsv has died */
  293. sv[i].pid = 0;
  294. need_rescan = 1;
  295. }
  296. }
  297. }
  298. now = monotonic_sec();
  299. if ((int)(now - stampcheck) >= 0) {
  300. /* wait at least a second */
  301. stampcheck = now + 1;
  302. if (stat(svdir, &s) != -1) {
  303. if (need_rescan || s.st_mtime != last_mtime
  304. || s.st_ino != last_ino || s.st_dev != last_dev
  305. ) {
  306. /* svdir modified */
  307. if (chdir(svdir) != -1) {
  308. last_mtime = s.st_mtime;
  309. last_dev = s.st_dev;
  310. last_ino = s.st_ino;
  311. /* if the svdir changed this very second, wait until the
  312. * next second, because we won't be able to detect more
  313. * changes within this second */
  314. while (time(NULL) == last_mtime)
  315. usleep(100000);
  316. need_rescan = do_rescan();
  317. while (fchdir(curdir) == -1) {
  318. warn2_cannot("change directory, pausing", "");
  319. sleep(5);
  320. }
  321. } else {
  322. warn2_cannot("change directory to ", svdir);
  323. }
  324. }
  325. } else {
  326. warn2_cannot("stat ", svdir);
  327. }
  328. }
  329. #if ENABLE_FEATURE_RUNSVDIR_LOG
  330. if (rplog) {
  331. if ((int)(now - stamplog) >= 0) {
  332. write(logpipe.wr, ".", 1);
  333. stamplog = now + 900;
  334. }
  335. }
  336. pfd[0].revents = 0;
  337. #endif
  338. {
  339. unsigned deadline = (need_rescan ? 1 : 5);
  340. #if ENABLE_FEATURE_RUNSVDIR_LOG
  341. if (rplog)
  342. poll(pfd, 1, deadline*1000);
  343. else
  344. #endif
  345. sleep(deadline);
  346. }
  347. #if ENABLE_FEATURE_RUNSVDIR_LOG
  348. if (pfd[0].revents & POLLIN) {
  349. char ch;
  350. while (read(logpipe.rd, &ch, 1) > 0) {
  351. if (ch < ' ')
  352. ch = ' ';
  353. for (i = 6; rplog[i] != '\0'; i++)
  354. rplog[i-1] = rplog[i];
  355. rplog[i-1] = ch;
  356. }
  357. }
  358. #endif
  359. sig = bb_got_signal;
  360. if (!sig)
  361. continue;
  362. bb_got_signal = 0;
  363. /* -s SCRIPT: useful if we are init.
  364. * In this case typically script never returns,
  365. * it halts/powers off/reboots the system. */
  366. if (opt_s_argv[0]) {
  367. pid_t pid;
  368. /* Single parameter: signal# */
  369. opt_s_argv[1] = utoa(sig);
  370. pid = spawn(opt_s_argv);
  371. if (pid > 0) {
  372. /* Remembering to wait for _any_ children,
  373. * not just pid */
  374. while (wait(NULL) != pid)
  375. continue;
  376. }
  377. }
  378. if (sig == SIGHUP) {
  379. for (i = 0; i < svnum; i++)
  380. if (sv[i].pid)
  381. kill(sv[i].pid, SIGTERM);
  382. }
  383. /* SIGHUP or SIGTERM (or SIGUSRn if we are init) */
  384. /* Exit unless we are init */
  385. if (!i_am_init)
  386. return (SIGHUP == sig) ? 111 : EXIT_SUCCESS;
  387. /* init continues to monitor services forever */
  388. } /* for (;;) */
  389. }