sv.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. /* Taken from http://smarden.sunsite.dk/runit/sv.8.html:
  25. sv - control and manage services monitored by runsv
  26. sv [-v] [-w sec] command services
  27. /etc/init.d/service [-w sec] command
  28. The sv program reports the current status and controls the state of services
  29. monitored by the runsv(8) supervisor.
  30. services consists of one or more arguments, each argument naming a directory
  31. service used by runsv(8). If service doesn't start with a dot or slash,
  32. it is searched in the default services directory /var/service/, otherwise
  33. relative to the current directory.
  34. command is one of up, down, status, once, pause, cont, hup, alarm, interrupt,
  35. 1, 2, term, kill, or exit, or start, stop, restart, shutdown, force-stop,
  36. force-reload, force-restart, force-shutdown.
  37. The sv program can be sym-linked to /etc/init.d/ to provide an LSB init
  38. script interface. The service to be controlled then is specified by the
  39. base name of the "init script".
  40. status
  41. Report the current status of the service, and the appendant log service
  42. if available, to standard output.
  43. up
  44. If the service is not running, start it. If the service stops, restart it.
  45. down
  46. If the service is running, send it the TERM signal, and the CONT signal.
  47. If ./run exits, start ./finish if it exists. After it stops, do not
  48. restart service.
  49. once
  50. If the service is not running, start it. Do not restart it if it stops.
  51. pause cont hup alarm interrupt quit 1 2 term kill
  52. If the service is running, send it the STOP, CONT, HUP, ALRM, INT, QUIT,
  53. USR1, USR2, TERM, or KILL signal respectively.
  54. exit
  55. If the service is running, send it the TERM signal, and the CONT signal.
  56. Do not restart the service. If the service is down, and no log service
  57. exists, runsv(8) exits. If the service is down and a log service exists,
  58. send the TERM signal to the log service. If the log service is down,
  59. runsv(8) exits. This command is ignored if it is given to an appendant
  60. log service.
  61. sv actually looks only at the first character of above commands.
  62. Commands compatible to LSB init script actions:
  63. status
  64. Same as status.
  65. start
  66. Same as up, but wait up to 7 seconds for the command to take effect.
  67. Then report the status or timeout. If the script ./check exists in
  68. the service directory, sv runs this script to check whether the service
  69. is up and available; it's considered to be available if ./check exits
  70. with 0.
  71. stop
  72. Same as down, but wait up to 7 seconds for the service to become down.
  73. Then report the status or timeout.
  74. restart
  75. Send the commands term, cont, and up to the service, and wait up to
  76. 7 seconds for the service to restart. Then report the status or timeout.
  77. If the script ./check exists in the service directory, sv runs this script
  78. to check whether the service is up and available again; it's considered
  79. to be available if ./check exits with 0.
  80. shutdown
  81. Same as exit, but wait up to 7 seconds for the runsv(8) process
  82. to terminate. Then report the status or timeout.
  83. force-stop
  84. Same as down, but wait up to 7 seconds for the service to become down.
  85. Then report the status, and on timeout send the service the kill command.
  86. force-reload
  87. Send the service the term and cont commands, and wait up to
  88. 7 seconds for the service to restart. Then report the status,
  89. and on timeout send the service the kill command.
  90. force-restart
  91. Send the service the term, cont and up commands, and wait up to
  92. 7 seconds for the service to restart. Then report the status, and
  93. on timeout send the service the kill command. If the script ./check
  94. exists in the service directory, sv runs this script to check whether
  95. the service is up and available again; it's considered to be available
  96. if ./check exits with 0.
  97. force-shutdown
  98. Same as exit, but wait up to 7 seconds for the runsv(8) process to
  99. terminate. Then report the status, and on timeout send the service
  100. the kill command.
  101. Additional Commands
  102. check
  103. Check for the service to be in the state that's been requested. Wait up to
  104. 7 seconds for the service to reach the requested state, then report
  105. the status or timeout. If the requested state of the service is up,
  106. and the script ./check exists in the service directory, sv runs
  107. this script to check whether the service is up and running;
  108. it's considered to be up if ./check exits with 0.
  109. Options
  110. -v
  111. wait up to 7 seconds for the command to take effect.
  112. Then report the status or timeout.
  113. -w sec
  114. Override the default timeout of 7 seconds with sec seconds. Implies -v.
  115. Environment
  116. SVDIR
  117. The environment variable $SVDIR overrides the default services directory
  118. /var/service.
  119. SVWAIT
  120. The environment variable $SVWAIT overrides the default 7 seconds to wait
  121. for a command to take effect. It is overridden by the -w option.
  122. Exit Codes
  123. sv exits 0, if the command was successfully sent to all services, and,
  124. if it was told to wait, the command has taken effect to all services.
  125. For each service that caused an error (e.g. the directory is not
  126. controlled by a runsv(8) process, or sv timed out while waiting),
  127. sv increases the exit code by one and exits non zero. The maximum
  128. is 99. sv exits 100 on error.
  129. */
  130. /* Busyboxed by Denys Vlasenko <vda.linux@googlemail.com> */
  131. /* TODO: depends on runit_lib.c - review and reduce/eliminate */
  132. #include <sys/poll.h>
  133. #include <sys/file.h>
  134. #include "libbb.h"
  135. #include "runit_lib.h"
  136. struct globals {
  137. const char *acts;
  138. char **service;
  139. unsigned rc;
  140. /* "Bernstein" time format: unix + 0x400000000000000aULL */
  141. uint64_t tstart, tnow;
  142. svstatus_t svstatus;
  143. } FIX_ALIASING;
  144. #define G (*(struct globals*)&bb_common_bufsiz1)
  145. #define acts (G.acts )
  146. #define service (G.service )
  147. #define rc (G.rc )
  148. #define tstart (G.tstart )
  149. #define tnow (G.tnow )
  150. #define svstatus (G.svstatus )
  151. #define INIT_G() do { } while (0)
  152. static void fatal_cannot(const char *m1) NORETURN;
  153. static void fatal_cannot(const char *m1)
  154. {
  155. bb_perror_msg("fatal: can't %s", m1);
  156. _exit(151);
  157. }
  158. static void out(const char *p, const char *m1)
  159. {
  160. printf("%s%s: %s", p, *service, m1);
  161. if (errno) {
  162. printf(": %s", strerror(errno));
  163. }
  164. bb_putchar('\n'); /* will also flush the output */
  165. }
  166. #define WARN "warning: "
  167. #define OK "ok: "
  168. static void fail(const char *m1)
  169. {
  170. ++rc;
  171. out("fail: ", m1);
  172. }
  173. static void failx(const char *m1)
  174. {
  175. errno = 0;
  176. fail(m1);
  177. }
  178. static void warn(const char *m1)
  179. {
  180. ++rc;
  181. /* "warning: <service>: <m1>\n" */
  182. out("warning: ", m1);
  183. }
  184. static void ok(const char *m1)
  185. {
  186. errno = 0;
  187. out(OK, m1);
  188. }
  189. static int svstatus_get(void)
  190. {
  191. int fd, r;
  192. fd = open_write("supervise/ok");
  193. if (fd == -1) {
  194. if (errno == ENODEV) {
  195. *acts == 'x' ? ok("runsv not running")
  196. : failx("runsv not running");
  197. return 0;
  198. }
  199. warn("can't open supervise/ok");
  200. return -1;
  201. }
  202. close(fd);
  203. fd = open_read("supervise/status");
  204. if (fd == -1) {
  205. warn("can't open supervise/status");
  206. return -1;
  207. }
  208. r = read(fd, &svstatus, 20);
  209. close(fd);
  210. switch (r) {
  211. case 20:
  212. break;
  213. case -1:
  214. warn("can't read supervise/status");
  215. return -1;
  216. default:
  217. errno = 0;
  218. warn("can't read supervise/status: bad format");
  219. return -1;
  220. }
  221. return 1;
  222. }
  223. static unsigned svstatus_print(const char *m)
  224. {
  225. int diff;
  226. int pid;
  227. int normallyup = 0;
  228. struct stat s;
  229. uint64_t timestamp;
  230. if (stat("down", &s) == -1) {
  231. if (errno != ENOENT) {
  232. bb_perror_msg(WARN"can't stat %s/down", *service);
  233. return 0;
  234. }
  235. normallyup = 1;
  236. }
  237. pid = SWAP_LE32(svstatus.pid_le32);
  238. timestamp = SWAP_BE64(svstatus.time_be64);
  239. if (pid) {
  240. switch (svstatus.run_or_finish) {
  241. case 1: printf("run: "); break;
  242. case 2: printf("finish: "); break;
  243. }
  244. printf("%s: (pid %d) ", m, pid);
  245. } else {
  246. printf("down: %s: ", m);
  247. }
  248. diff = tnow - timestamp;
  249. printf("%us", (diff < 0 ? 0 : diff));
  250. if (pid) {
  251. if (!normallyup) printf(", normally down");
  252. if (svstatus.paused) printf(", paused");
  253. if (svstatus.want == 'd') printf(", want down");
  254. if (svstatus.got_term) printf(", got TERM");
  255. } else {
  256. if (normallyup) printf(", normally up");
  257. if (svstatus.want == 'u') printf(", want up");
  258. }
  259. return pid ? 1 : 2;
  260. }
  261. static int status(const char *unused UNUSED_PARAM)
  262. {
  263. int r;
  264. if (svstatus_get() <= 0)
  265. return 0;
  266. r = svstatus_print(*service);
  267. if (chdir("log") == -1) {
  268. if (errno != ENOENT) {
  269. printf("; log: "WARN"can't change to log service directory: %s",
  270. strerror(errno));
  271. }
  272. } else if (svstatus_get()) {
  273. printf("; ");
  274. svstatus_print("log");
  275. }
  276. bb_putchar('\n'); /* will also flush the output */
  277. return r;
  278. }
  279. static int checkscript(void)
  280. {
  281. char *prog[2];
  282. struct stat s;
  283. int pid, w;
  284. if (stat("check", &s) == -1) {
  285. if (errno == ENOENT) return 1;
  286. bb_perror_msg(WARN"can't stat %s/check", *service);
  287. return 0;
  288. }
  289. /* if (!(s.st_mode & S_IXUSR)) return 1; */
  290. prog[0] = (char*)"./check";
  291. prog[1] = NULL;
  292. pid = spawn(prog);
  293. if (pid <= 0) {
  294. bb_perror_msg(WARN"can't %s child %s/check", "run", *service);
  295. return 0;
  296. }
  297. while (safe_waitpid(pid, &w, 0) == -1) {
  298. bb_perror_msg(WARN"can't %s child %s/check", "wait for", *service);
  299. return 0;
  300. }
  301. return WEXITSTATUS(w) == 0;
  302. }
  303. static int check(const char *a)
  304. {
  305. int r;
  306. unsigned pid_le32;
  307. uint64_t timestamp;
  308. r = svstatus_get();
  309. if (r == -1)
  310. return -1;
  311. if (r == 0) {
  312. if (*a == 'x')
  313. return 1;
  314. return -1;
  315. }
  316. pid_le32 = svstatus.pid_le32;
  317. switch (*a) {
  318. case 'x':
  319. return 0;
  320. case 'u':
  321. if (!pid_le32 || svstatus.run_or_finish != 1) return 0;
  322. if (!checkscript()) return 0;
  323. break;
  324. case 'd':
  325. if (pid_le32) return 0;
  326. break;
  327. case 'c':
  328. if (pid_le32 && !checkscript()) return 0;
  329. break;
  330. case 't':
  331. if (!pid_le32 && svstatus.want == 'd') break;
  332. timestamp = SWAP_BE64(svstatus.time_be64);
  333. if ((tstart > timestamp) || !pid_le32 || svstatus.got_term || !checkscript())
  334. return 0;
  335. break;
  336. case 'o':
  337. timestamp = SWAP_BE64(svstatus.time_be64);
  338. if ((!pid_le32 && tstart > timestamp) || (pid_le32 && svstatus.want != 'd'))
  339. return 0;
  340. }
  341. printf(OK);
  342. svstatus_print(*service);
  343. bb_putchar('\n'); /* will also flush the output */
  344. return 1;
  345. }
  346. static int control(const char *a)
  347. {
  348. int fd, r, l;
  349. /* Is it an optimization?
  350. It causes problems with "sv o SRV; ...; sv d SRV"
  351. ('d' is not passed to SRV because its .want == 'd'):
  352. if (svstatus_get() <= 0)
  353. return -1;
  354. if (svstatus.want == *a)
  355. return 0;
  356. */
  357. fd = open_write("supervise/control");
  358. if (fd == -1) {
  359. if (errno != ENODEV)
  360. warn("can't open supervise/control");
  361. else
  362. *a == 'x' ? ok("runsv not running") : failx("runsv not running");
  363. return -1;
  364. }
  365. l = strlen(a);
  366. r = write(fd, a, l);
  367. close(fd);
  368. if (r != l) {
  369. warn("can't write to supervise/control");
  370. return -1;
  371. }
  372. return 1;
  373. }
  374. int sv_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  375. int sv_main(int argc UNUSED_PARAM, char **argv)
  376. {
  377. unsigned opt;
  378. char *x;
  379. char *action;
  380. const char *varservice = CONFIG_SV_DEFAULT_SERVICE_DIR;
  381. unsigned waitsec = 7;
  382. smallint kll = 0;
  383. int verbose = 0;
  384. int (*act)(const char*);
  385. int (*cbk)(const char*);
  386. int curdir;
  387. INIT_G();
  388. xfunc_error_retval = 100;
  389. x = getenv("SVDIR");
  390. if (x) varservice = x;
  391. x = getenv("SVWAIT");
  392. if (x) waitsec = xatou(x);
  393. opt_complementary = "w+:vv"; /* -w N, -v is a counter */
  394. opt = getopt32(argv, "w:v", &waitsec, &verbose);
  395. argv += optind;
  396. action = *argv++;
  397. if (!action || !*argv) bb_show_usage();
  398. tnow = time(NULL) + 0x400000000000000aULL;
  399. tstart = tnow;
  400. curdir = open_read(".");
  401. if (curdir == -1)
  402. fatal_cannot("open current directory");
  403. act = &control;
  404. acts = "s";
  405. cbk = &check;
  406. switch (*action) {
  407. case 'x':
  408. case 'e':
  409. acts = "x";
  410. if (!verbose) cbk = NULL;
  411. break;
  412. case 'X':
  413. case 'E':
  414. acts = "x";
  415. kll = 1;
  416. break;
  417. case 'D':
  418. acts = "d";
  419. kll = 1;
  420. break;
  421. case 'T':
  422. acts = "tc";
  423. kll = 1;
  424. break;
  425. case 'c':
  426. if (str_equal(action, "check")) {
  427. act = NULL;
  428. acts = "c";
  429. break;
  430. }
  431. case 'u': case 'd': case 'o': case 't': case 'p': case 'h':
  432. case 'a': case 'i': case 'k': case 'q': case '1': case '2':
  433. action[1] = '\0';
  434. acts = action;
  435. if (!verbose) cbk = NULL;
  436. break;
  437. case 's':
  438. if (str_equal(action, "shutdown")) {
  439. acts = "x";
  440. break;
  441. }
  442. if (str_equal(action, "start")) {
  443. acts = "u";
  444. break;
  445. }
  446. if (str_equal(action, "stop")) {
  447. acts = "d";
  448. break;
  449. }
  450. /* "status" */
  451. act = &status;
  452. cbk = NULL;
  453. break;
  454. case 'r':
  455. if (str_equal(action, "restart")) {
  456. acts = "tcu";
  457. break;
  458. }
  459. bb_show_usage();
  460. case 'f':
  461. if (str_equal(action, "force-reload")) {
  462. acts = "tc";
  463. kll = 1;
  464. break;
  465. }
  466. if (str_equal(action, "force-restart")) {
  467. acts = "tcu";
  468. kll = 1;
  469. break;
  470. }
  471. if (str_equal(action, "force-shutdown")) {
  472. acts = "x";
  473. kll = 1;
  474. break;
  475. }
  476. if (str_equal(action, "force-stop")) {
  477. acts = "d";
  478. kll = 1;
  479. break;
  480. }
  481. default:
  482. bb_show_usage();
  483. }
  484. service = argv;
  485. while ((x = *service) != NULL) {
  486. if (x[0] != '/' && x[0] != '.') {
  487. if (chdir(varservice) == -1)
  488. goto chdir_failed_0;
  489. }
  490. if (chdir(x) == -1) {
  491. chdir_failed_0:
  492. fail("can't change to service directory");
  493. goto nullify_service_0;
  494. }
  495. if (act && (act(acts) == -1)) {
  496. nullify_service_0:
  497. *service = (char*) -1L; /* "dead" */
  498. }
  499. if (fchdir(curdir) == -1)
  500. fatal_cannot("change to original directory");
  501. service++;
  502. }
  503. if (cbk) while (1) {
  504. int want_exit;
  505. int diff;
  506. diff = tnow - tstart;
  507. service = argv;
  508. want_exit = 1;
  509. while ((x = *service) != NULL) {
  510. if (x == (char*) -1L) /* "dead" */
  511. goto next;
  512. if (x[0] != '/' && x[0] != '.') {
  513. if (chdir(varservice) == -1)
  514. goto chdir_failed;
  515. }
  516. if (chdir(x) == -1) {
  517. chdir_failed:
  518. fail("can't change to service directory");
  519. goto nullify_service;
  520. }
  521. if (cbk(acts) != 0)
  522. goto nullify_service;
  523. want_exit = 0;
  524. if (diff >= waitsec) {
  525. printf(kll ? "kill: " : "timeout: ");
  526. if (svstatus_get() > 0) {
  527. svstatus_print(x);
  528. ++rc;
  529. }
  530. bb_putchar('\n'); /* will also flush the output */
  531. if (kll)
  532. control("k");
  533. nullify_service:
  534. *service = (char*) -1L; /* "dead" */
  535. }
  536. if (fchdir(curdir) == -1)
  537. fatal_cannot("change to original directory");
  538. next:
  539. service++;
  540. }
  541. if (want_exit) break;
  542. usleep(420000);
  543. tnow = time(NULL) + 0x400000000000000aULL;
  544. }
  545. return rc > 99 ? 99 : rc;
  546. }