s6-user-init 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #!/bin/sh --
  2. # vim: ft=sh
  3. set -ue
  4. : "${XDG_RUNTIME_DIR:=${TMPDIR:-/tmp}/runtime-${USER:-$(id -un)}}"
  5. : "${XDG_DATA_HOME:=${HOME:?}/.local/share}"
  6. : "${S6_SYSPATH:=${XDG_DATA_HOME}/s6/user}"
  7. : "${S6_RUNPATH:=${XDG_RUNTIME_DIR}/s6/user}"
  8. : "${S6_LIVE:=${S6_RUNPATH}/s6-rc}"
  9. : "${S6_COMPILED:=${S6_SYSPATH}/rc/compiled}"
  10. : "${S6_SVDIR:=${S6_RUNPATH}/service}"
  11. : "${S6_CONFIG_DIR:=${S6_SYSPATH}/config}"
  12. : "${S6_LOG_DIR:=${S6_RUNPATH}/log}"
  13. : "${S6_OWNER_PID_FILE:=${S6_SVDIR}/.s6-svscan/owner.pid}"
  14. : "${S6_WAIT_FOR_STOP_MS:=1000}" # how many miliseconds wait for services to stop
  15. unexport_env() {
  16. # unexport unneeded variables that may be exported to configure this script
  17. # for example if run as:
  18. # S6_RUNPATH=some/other/path s6-user-init start ...
  19. unset \
  20. S6_RUNPATH \
  21. S6_LIVE \
  22. S6_COMPILED \
  23. S6_SVDIR \
  24. S6_OWNER_PID_FILE \
  25. S6_WAIT_FOR_STOP_MS
  26. }
  27. start() {
  28. pid="${1:?}"
  29. mkdir -p "${S6_SVDIR}"
  30. if s6-svscanctl -a "${S6_SVDIR}" 2>/dev/null; then
  31. echo "s6-svscan already running on '${S6_SVDIR}'" 1>&2
  32. exit 1
  33. fi
  34. echo "${pid}" | install -Dm600 /proc/self/fd/0 "${S6_OWNER_PID_FILE}"
  35. export S6_CONFIG_DIR
  36. export S6_LOG_DIR
  37. export S6_SYSPATH
  38. live="${S6_LIVE}"
  39. compiled="${S6_COMPILED}"
  40. svdir="${S6_SVDIR}"
  41. unexport_env
  42. exec s6-rc-svscan \
  43. -l "${live}" \
  44. -c "${compiled}" \
  45. -s "${svdir}"
  46. }
  47. stop() {
  48. pid="${1:?}"
  49. [ -f "${S6_OWNER_PID_FILE}" ] || {
  50. echo "pid file does not exist: '${S6_OWNER_PID_FILE}'" 1>&2
  51. exit 1
  52. }
  53. IFS= read -r owner <"${S6_OWNER_PID_FILE}"
  54. [ "${owner}" = "${pid}" ]
  55. s6-rc -l "${S6_LIVE}" -bda change || : # stop all services
  56. (
  57. cd "${S6_SVDIR}" &&
  58. exec s6-svwait -D -t "${S6_WAIT_FOR_STOP_MS}" ./* 2>/dev/null
  59. ) || : # wati for services to stop
  60. s6-svscanctl -n "${S6_SVDIR}" || : # stop svscan
  61. cd "${S6_LIVE%/*}"
  62. dir="$(readlink "${S6_LIVE}")"
  63. rm -rf -- "${dir:?}"
  64. unlink "${S6_LIVE}"
  65. rm -rf -- "${S6_SVDIR:?}"
  66. }
  67. usage() {
  68. printf '%s\n' \
  69. "Usage: ${0##*/} [action]" \
  70. ' start <pid> - start user services' \
  71. ' stop <pid> - stop user services' \
  72. ' help - show this help'
  73. exit "${1:-0}"
  74. }
  75. case "${1:?}" in
  76. start) start "${2:?provide owner pid}" ;;
  77. stop) stop "${2:?provide owner pid}" ;;
  78. help | -h) usage 0 ;;
  79. *) usage 1 ;;
  80. esac