3
0

sv.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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. };
  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) ATTRIBUTE_NORETURN;
  153. static void fatal_cannot(const char *m1)
  154. {
  155. bb_perror_msg("fatal: cannot %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("cannot open supervise/ok");
  200. return -1;
  201. }
  202. close(fd);
  203. fd = open_read("supervise/status");
  204. if (fd == -1) {
  205. warn("cannot 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("cannot read supervise/status");
  215. return -1;
  216. default:
  217. errno = 0;
  218. warn("cannot 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"cannot 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 ATTRIBUTE_UNUSED)
  262. {
  263. int r;
  264. r = svstatus_get();
  265. switch (r) { case -1: case 0: return 0; }
  266. r = svstatus_print(*service);
  267. if (chdir("log") == -1) {
  268. if (errno != ENOENT) {
  269. printf("; log: "WARN"cannot 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"cannot 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"cannot %s child %s/check", "run", *service);
  295. return 0;
  296. }
  297. while (safe_waitpid(pid, &w, 0) == -1) {
  298. bb_perror_msg(WARN"cannot %s child %s/check", "wait for", *service);
  299. return 0;
  300. }
  301. return !wait_exitcode(w);
  302. }
  303. static int check(const char *a)
  304. {
  305. int r;
  306. unsigned pid;
  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 = SWAP_LE32(svstatus.pid_le32);
  317. switch (*a) {
  318. case 'x':
  319. return 0;
  320. case 'u':
  321. if (!pid || svstatus.run_or_finish != 1) return 0;
  322. if (!checkscript()) return 0;
  323. break;
  324. case 'd':
  325. if (pid) return 0;
  326. break;
  327. case 'c':
  328. if (pid && !checkscript()) return 0;
  329. break;
  330. case 't':
  331. if (!pid && svstatus.want == 'd') break;
  332. timestamp = SWAP_BE64(svstatus.time_be64);
  333. if ((tstart > timestamp) || !pid || svstatus.got_term || !checkscript())
  334. return 0;
  335. break;
  336. case 'o':
  337. timestamp = SWAP_BE64(svstatus.time_be64);
  338. if ((!pid && tstart > timestamp) || (pid && 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;
  349. if (svstatus_get() <= 0)
  350. return -1;
  351. if (svstatus.want == *a)
  352. return 0;
  353. fd = open_write("supervise/control");
  354. if (fd == -1) {
  355. if (errno != ENODEV)
  356. warn("cannot open supervise/control");
  357. else
  358. *a == 'x' ? ok("runsv not running") : failx("runsv not running");
  359. return -1;
  360. }
  361. r = write(fd, a, strlen(a));
  362. close(fd);
  363. if (r != strlen(a)) {
  364. warn("cannot write to supervise/control");
  365. return -1;
  366. }
  367. return 1;
  368. }
  369. int sv_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  370. int sv_main(int argc, char **argv)
  371. {
  372. unsigned opt;
  373. unsigned i, want_exit;
  374. char *x;
  375. char *action;
  376. const char *varservice = "/var/service/";
  377. unsigned services;
  378. char **servicex;
  379. unsigned waitsec = 7;
  380. smallint kll = 0;
  381. int verbose = 0;
  382. int (*act)(const char*);
  383. int (*cbk)(const char*);
  384. int curdir;
  385. INIT_G();
  386. xfunc_error_retval = 100;
  387. x = getenv("SVDIR");
  388. if (x) varservice = x;
  389. x = getenv("SVWAIT");
  390. if (x) waitsec = xatou(x);
  391. opt_complementary = "w+:vv"; /* -w N, -v is a counter */
  392. opt = getopt32(argv, "w:v", &waitsec, &verbose);
  393. argc -= optind;
  394. argv += optind;
  395. action = *argv++;
  396. if (!action || !*argv) bb_show_usage();
  397. service = argv;
  398. services = argc - 1;
  399. tnow = time(0) + 0x400000000000000aULL;
  400. tstart = tnow;
  401. curdir = open_read(".");
  402. if (curdir == -1)
  403. fatal_cannot("open current directory");
  404. act = &control;
  405. acts = "s";
  406. cbk = &check;
  407. switch (*action) {
  408. case 'x':
  409. case 'e':
  410. acts = "x";
  411. if (!verbose) cbk = NULL;
  412. break;
  413. case 'X':
  414. case 'E':
  415. acts = "x";
  416. kll = 1;
  417. break;
  418. case 'D':
  419. acts = "d";
  420. kll = 1;
  421. break;
  422. case 'T':
  423. acts = "tc";
  424. kll = 1;
  425. break;
  426. case 'c':
  427. if (str_equal(action, "check")) {
  428. act = NULL;
  429. acts = "c";
  430. break;
  431. }
  432. case 'u': case 'd': case 'o': case 't': case 'p': case 'h':
  433. case 'a': case 'i': case 'k': case 'q': case '1': case '2':
  434. action[1] = '\0';
  435. acts = action;
  436. if (!verbose) cbk = NULL;
  437. break;
  438. case 's':
  439. if (str_equal(action, "shutdown")) {
  440. acts = "x";
  441. break;
  442. }
  443. if (str_equal(action, "start")) {
  444. acts = "u";
  445. break;
  446. }
  447. if (str_equal(action, "stop")) {
  448. acts = "d";
  449. break;
  450. }
  451. /* "status" */
  452. act = &status;
  453. cbk = NULL;
  454. break;
  455. case 'r':
  456. if (str_equal(action, "restart")) {
  457. acts = "tcu";
  458. break;
  459. }
  460. bb_show_usage();
  461. case 'f':
  462. if (str_equal(action, "force-reload")) {
  463. acts = "tc";
  464. kll = 1;
  465. break;
  466. }
  467. if (str_equal(action, "force-restart")) {
  468. acts = "tcu";
  469. kll = 1;
  470. break;
  471. }
  472. if (str_equal(action, "force-shutdown")) {
  473. acts = "x";
  474. kll = 1;
  475. break;
  476. }
  477. if (str_equal(action, "force-stop")) {
  478. acts = "d";
  479. kll = 1;
  480. break;
  481. }
  482. default:
  483. bb_show_usage();
  484. }
  485. servicex = service;
  486. for (i = 0; i < services; ++i) {
  487. if ((**service != '/') && (**service != '.')) {
  488. if (chdir(varservice) == -1)
  489. goto chdir_failed_0;
  490. }
  491. if (chdir(*service) == -1) {
  492. chdir_failed_0:
  493. fail("cannot change to service directory");
  494. goto nullify_service_0;
  495. }
  496. if (act && (act(acts) == -1)) {
  497. nullify_service_0:
  498. *service = NULL;
  499. }
  500. if (fchdir(curdir) == -1)
  501. fatal_cannot("change to original directory");
  502. service++;
  503. }
  504. if (cbk) while (1) {
  505. int diff;
  506. diff = tnow - tstart;
  507. service = servicex;
  508. want_exit = 1;
  509. for (i = 0; i < services; ++i, ++service) {
  510. if (!*service)
  511. continue;
  512. if ((**service != '/') && (**service != '.')) {
  513. if (chdir(varservice) == -1)
  514. goto chdir_failed;
  515. }
  516. if (chdir(*service) == -1) {
  517. chdir_failed:
  518. fail("cannot 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(*service);
  528. ++rc;
  529. }
  530. bb_putchar('\n'); /* will also flush the output */
  531. if (kll)
  532. control("k");
  533. nullify_service:
  534. *service = NULL;
  535. }
  536. if (fchdir(curdir) == -1)
  537. fatal_cannot("change to original directory");
  538. }
  539. if (want_exit) break;
  540. usleep(420000);
  541. tnow = time(0) + 0x400000000000000aULL;
  542. }
  543. return rc > 99 ? 99 : rc;
  544. }