sv.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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. //usage:#define sv_trivial_usage
  133. //usage: "[-v] [-w SEC] CMD SERVICE_DIR..."
  134. //usage:#define sv_full_usage "\n\n"
  135. //usage: "Control services monitored by runsv supervisor.\n"
  136. //usage: "Commands (only first character is enough):\n"
  137. //usage: "\n"
  138. //usage: "status: query service status\n"
  139. //usage: "up: if service isn't running, start it. If service stops, restart it\n"
  140. //usage: "once: like 'up', but if service stops, don't restart it\n"
  141. //usage: "down: send TERM and CONT signals. If ./run exits, start ./finish\n"
  142. //usage: " if it exists. After it stops, don't restart service\n"
  143. //usage: "exit: send TERM and CONT signals to service and log service. If they exit,\n"
  144. //usage: " runsv exits too\n"
  145. //usage: "pause, cont, hup, alarm, interrupt, quit, 1, 2, term, kill: send\n"
  146. //usage: "STOP, CONT, HUP, ALRM, INT, QUIT, USR1, USR2, TERM, KILL signal to service"
  147. #include <sys/poll.h>
  148. #include <sys/file.h>
  149. #include "libbb.h"
  150. #include "runit_lib.h"
  151. struct globals {
  152. const char *acts;
  153. char **service;
  154. unsigned rc;
  155. /* "Bernstein" time format: unix + 0x400000000000000aULL */
  156. uint64_t tstart, tnow;
  157. svstatus_t svstatus;
  158. } FIX_ALIASING;
  159. #define G (*(struct globals*)&bb_common_bufsiz1)
  160. #define acts (G.acts )
  161. #define service (G.service )
  162. #define rc (G.rc )
  163. #define tstart (G.tstart )
  164. #define tnow (G.tnow )
  165. #define svstatus (G.svstatus )
  166. #define INIT_G() do { } while (0)
  167. #define str_equal(s,t) (!strcmp((s), (t)))
  168. static void fatal_cannot(const char *m1) NORETURN;
  169. static void fatal_cannot(const char *m1)
  170. {
  171. bb_perror_msg("fatal: can't %s", m1);
  172. _exit(151);
  173. }
  174. static void out(const char *p, const char *m1)
  175. {
  176. printf("%s%s: %s", p, *service, m1);
  177. if (errno) {
  178. printf(": %s", strerror(errno));
  179. }
  180. bb_putchar('\n'); /* will also flush the output */
  181. }
  182. #define WARN "warning: "
  183. #define OK "ok: "
  184. static void fail(const char *m1)
  185. {
  186. ++rc;
  187. out("fail: ", m1);
  188. }
  189. static void failx(const char *m1)
  190. {
  191. errno = 0;
  192. fail(m1);
  193. }
  194. static void warn(const char *m1)
  195. {
  196. ++rc;
  197. /* "warning: <service>: <m1>\n" */
  198. out("warning: ", m1);
  199. }
  200. static void ok(const char *m1)
  201. {
  202. errno = 0;
  203. out(OK, m1);
  204. }
  205. static int svstatus_get(void)
  206. {
  207. int fd, r;
  208. fd = open("supervise/ok", O_WRONLY|O_NDELAY);
  209. if (fd == -1) {
  210. if (errno == ENODEV) {
  211. *acts == 'x' ? ok("runsv not running")
  212. : failx("runsv not running");
  213. return 0;
  214. }
  215. warn("can't open supervise/ok");
  216. return -1;
  217. }
  218. close(fd);
  219. fd = open("supervise/status", O_RDONLY|O_NDELAY);
  220. if (fd == -1) {
  221. warn("can't open supervise/status");
  222. return -1;
  223. }
  224. r = read(fd, &svstatus, 20);
  225. close(fd);
  226. switch (r) {
  227. case 20:
  228. break;
  229. case -1:
  230. warn("can't read supervise/status");
  231. return -1;
  232. default:
  233. errno = 0;
  234. warn("can't read supervise/status: bad format");
  235. return -1;
  236. }
  237. return 1;
  238. }
  239. static unsigned svstatus_print(const char *m)
  240. {
  241. int diff;
  242. int pid;
  243. int normallyup = 0;
  244. struct stat s;
  245. uint64_t timestamp;
  246. if (stat("down", &s) == -1) {
  247. if (errno != ENOENT) {
  248. bb_perror_msg(WARN"can't stat %s/down", *service);
  249. return 0;
  250. }
  251. normallyup = 1;
  252. }
  253. pid = SWAP_LE32(svstatus.pid_le32);
  254. timestamp = SWAP_BE64(svstatus.time_be64);
  255. if (pid) {
  256. switch (svstatus.run_or_finish) {
  257. case 1: printf("run: "); break;
  258. case 2: printf("finish: "); break;
  259. }
  260. printf("%s: (pid %d) ", m, pid);
  261. } else {
  262. printf("down: %s: ", m);
  263. }
  264. diff = tnow - timestamp;
  265. printf("%us", (diff < 0 ? 0 : diff));
  266. if (pid) {
  267. if (!normallyup) printf(", normally down");
  268. if (svstatus.paused) printf(", paused");
  269. if (svstatus.want == 'd') printf(", want down");
  270. if (svstatus.got_term) printf(", got TERM");
  271. } else {
  272. if (normallyup) printf(", normally up");
  273. if (svstatus.want == 'u') printf(", want up");
  274. }
  275. return pid ? 1 : 2;
  276. }
  277. static int status(const char *unused UNUSED_PARAM)
  278. {
  279. int r;
  280. if (svstatus_get() <= 0)
  281. return 0;
  282. r = svstatus_print(*service);
  283. if (chdir("log") == -1) {
  284. if (errno != ENOENT) {
  285. printf("; log: "WARN"can't change to log service directory: %s",
  286. strerror(errno));
  287. }
  288. } else if (svstatus_get()) {
  289. printf("; ");
  290. svstatus_print("log");
  291. }
  292. bb_putchar('\n'); /* will also flush the output */
  293. return r;
  294. }
  295. static int checkscript(void)
  296. {
  297. char *prog[2];
  298. struct stat s;
  299. int pid, w;
  300. if (stat("check", &s) == -1) {
  301. if (errno == ENOENT) return 1;
  302. bb_perror_msg(WARN"can't stat %s/check", *service);
  303. return 0;
  304. }
  305. /* if (!(s.st_mode & S_IXUSR)) return 1; */
  306. prog[0] = (char*)"./check";
  307. prog[1] = NULL;
  308. pid = spawn(prog);
  309. if (pid <= 0) {
  310. bb_perror_msg(WARN"can't %s child %s/check", "run", *service);
  311. return 0;
  312. }
  313. while (safe_waitpid(pid, &w, 0) == -1) {
  314. bb_perror_msg(WARN"can't %s child %s/check", "wait for", *service);
  315. return 0;
  316. }
  317. return WEXITSTATUS(w) == 0;
  318. }
  319. static int check(const char *a)
  320. {
  321. int r;
  322. unsigned pid_le32;
  323. uint64_t timestamp;
  324. r = svstatus_get();
  325. if (r == -1)
  326. return -1;
  327. if (r == 0) {
  328. if (*a == 'x')
  329. return 1;
  330. return -1;
  331. }
  332. pid_le32 = svstatus.pid_le32;
  333. switch (*a) {
  334. case 'x':
  335. return 0;
  336. case 'u':
  337. if (!pid_le32 || svstatus.run_or_finish != 1) return 0;
  338. if (!checkscript()) return 0;
  339. break;
  340. case 'd':
  341. if (pid_le32) return 0;
  342. break;
  343. case 'c':
  344. if (pid_le32 && !checkscript()) return 0;
  345. break;
  346. case 't':
  347. if (!pid_le32 && svstatus.want == 'd') break;
  348. timestamp = SWAP_BE64(svstatus.time_be64);
  349. if ((tstart > timestamp) || !pid_le32 || svstatus.got_term || !checkscript())
  350. return 0;
  351. break;
  352. case 'o':
  353. timestamp = SWAP_BE64(svstatus.time_be64);
  354. if ((!pid_le32 && tstart > timestamp) || (pid_le32 && svstatus.want != 'd'))
  355. return 0;
  356. }
  357. printf(OK);
  358. svstatus_print(*service);
  359. bb_putchar('\n'); /* will also flush the output */
  360. return 1;
  361. }
  362. static int control(const char *a)
  363. {
  364. int fd, r, l;
  365. /* Is it an optimization?
  366. It causes problems with "sv o SRV; ...; sv d SRV"
  367. ('d' is not passed to SRV because its .want == 'd'):
  368. if (svstatus_get() <= 0)
  369. return -1;
  370. if (svstatus.want == *a)
  371. return 0;
  372. */
  373. fd = open("supervise/control", O_WRONLY|O_NDELAY);
  374. if (fd == -1) {
  375. if (errno != ENODEV)
  376. warn("can't open supervise/control");
  377. else
  378. *a == 'x' ? ok("runsv not running") : failx("runsv not running");
  379. return -1;
  380. }
  381. l = strlen(a);
  382. r = write(fd, a, l);
  383. close(fd);
  384. if (r != l) {
  385. warn("can't write to supervise/control");
  386. return -1;
  387. }
  388. return 1;
  389. }
  390. int sv_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  391. int sv_main(int argc UNUSED_PARAM, char **argv)
  392. {
  393. char *x;
  394. char *action;
  395. const char *varservice = CONFIG_SV_DEFAULT_SERVICE_DIR;
  396. unsigned waitsec = 7;
  397. smallint kll = 0;
  398. int verbose = 0;
  399. int (*act)(const char*);
  400. int (*cbk)(const char*);
  401. int curdir;
  402. INIT_G();
  403. xfunc_error_retval = 100;
  404. x = getenv("SVDIR");
  405. if (x) varservice = x;
  406. x = getenv("SVWAIT");
  407. if (x) waitsec = xatou(x);
  408. opt_complementary = "w+:vv"; /* -w N, -v is a counter */
  409. getopt32(argv, "w:v", &waitsec, &verbose);
  410. argv += optind;
  411. action = *argv++;
  412. if (!action || !*argv) bb_show_usage();
  413. tnow = time(NULL) + 0x400000000000000aULL;
  414. tstart = tnow;
  415. curdir = open(".", O_RDONLY|O_NDELAY);
  416. if (curdir == -1)
  417. fatal_cannot("open current directory");
  418. act = &control;
  419. acts = "s";
  420. cbk = &check;
  421. switch (*action) {
  422. case 'x':
  423. case 'e':
  424. acts = "x";
  425. if (!verbose) cbk = NULL;
  426. break;
  427. case 'X':
  428. case 'E':
  429. acts = "x";
  430. kll = 1;
  431. break;
  432. case 'D':
  433. acts = "d";
  434. kll = 1;
  435. break;
  436. case 'T':
  437. acts = "tc";
  438. kll = 1;
  439. break;
  440. case 'c':
  441. if (str_equal(action, "check")) {
  442. act = NULL;
  443. acts = "c";
  444. break;
  445. }
  446. case 'u': case 'd': case 'o': case 't': case 'p': case 'h':
  447. case 'a': case 'i': case 'k': case 'q': case '1': case '2':
  448. action[1] = '\0';
  449. acts = action;
  450. if (!verbose) cbk = NULL;
  451. break;
  452. case 's':
  453. if (str_equal(action, "shutdown")) {
  454. acts = "x";
  455. break;
  456. }
  457. if (str_equal(action, "start")) {
  458. acts = "u";
  459. break;
  460. }
  461. if (str_equal(action, "stop")) {
  462. acts = "d";
  463. break;
  464. }
  465. /* "status" */
  466. act = &status;
  467. cbk = NULL;
  468. break;
  469. case 'r':
  470. if (str_equal(action, "restart")) {
  471. acts = "tcu";
  472. break;
  473. }
  474. bb_show_usage();
  475. case 'f':
  476. if (str_equal(action, "force-reload")) {
  477. acts = "tc";
  478. kll = 1;
  479. break;
  480. }
  481. if (str_equal(action, "force-restart")) {
  482. acts = "tcu";
  483. kll = 1;
  484. break;
  485. }
  486. if (str_equal(action, "force-shutdown")) {
  487. acts = "x";
  488. kll = 1;
  489. break;
  490. }
  491. if (str_equal(action, "force-stop")) {
  492. acts = "d";
  493. kll = 1;
  494. break;
  495. }
  496. default:
  497. bb_show_usage();
  498. }
  499. service = argv;
  500. while ((x = *service) != NULL) {
  501. if (x[0] != '/' && x[0] != '.') {
  502. if (chdir(varservice) == -1)
  503. goto chdir_failed_0;
  504. }
  505. if (chdir(x) == -1) {
  506. chdir_failed_0:
  507. fail("can't change to service directory");
  508. goto nullify_service_0;
  509. }
  510. if (act && (act(acts) == -1)) {
  511. nullify_service_0:
  512. *service = (char*) -1L; /* "dead" */
  513. }
  514. if (fchdir(curdir) == -1)
  515. fatal_cannot("change to original directory");
  516. service++;
  517. }
  518. if (cbk) while (1) {
  519. int want_exit;
  520. int diff;
  521. diff = tnow - tstart;
  522. service = argv;
  523. want_exit = 1;
  524. while ((x = *service) != NULL) {
  525. if (x == (char*) -1L) /* "dead" */
  526. goto next;
  527. if (x[0] != '/' && x[0] != '.') {
  528. if (chdir(varservice) == -1)
  529. goto chdir_failed;
  530. }
  531. if (chdir(x) == -1) {
  532. chdir_failed:
  533. fail("can't change to service directory");
  534. goto nullify_service;
  535. }
  536. if (cbk(acts) != 0)
  537. goto nullify_service;
  538. want_exit = 0;
  539. if (diff >= waitsec) {
  540. printf(kll ? "kill: " : "timeout: ");
  541. if (svstatus_get() > 0) {
  542. svstatus_print(x);
  543. ++rc;
  544. }
  545. bb_putchar('\n'); /* will also flush the output */
  546. if (kll)
  547. control("k");
  548. nullify_service:
  549. *service = (char*) -1L; /* "dead" */
  550. }
  551. if (fchdir(curdir) == -1)
  552. fatal_cannot("change to original directory");
  553. next:
  554. service++;
  555. }
  556. if (want_exit) break;
  557. usleep(420000);
  558. tnow = time(NULL) + 0x400000000000000aULL;
  559. }
  560. return rc > 99 ? 99 : rc;
  561. }