service 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env bash
  2. set -o pipefail # trace ERR through pipes
  3. set -o errtrace # trace ERR through 'time command' and other functions
  4. set -o nounset ## set -u : exit the script if you try to use an uninitialised variable
  5. set -o errexit ## set -e : exit the script if any statement returns a non-true return value
  6. # Root check
  7. if [ "$(/usr/bin/whoami)" != "root" ]; then
  8. echo "[ERROR] Must be run as root"
  9. exit 1
  10. fi
  11. function serviceHelp() {
  12. echo "Usage: $(basename "$0") <servicename> <stop|start|restart|pid|status|check>"
  13. }
  14. function getServicePid() {
  15. local serviceName="$1"
  16. local servicePid=$(supervisorctl pid "${serviceName}:${serviceName}d")
  17. if [[ -z "$servicePid" ]] || [[ "$servicePid" == "0" ]]; then
  18. echo "not running"
  19. exit 1
  20. fi
  21. echo $servicePid
  22. }
  23. # Param check
  24. if [ "$#" -lt 2 ]; then
  25. echo "[ERROR] Missing parameters"
  26. serviceHelp
  27. exit 1
  28. fi
  29. #############################
  30. # Param init
  31. #############################
  32. SERVICENAME="$1"
  33. ACTION="$2"
  34. #############################
  35. # Service aliases
  36. #############################
  37. case "$SERVICENAME" in
  38. apache2|httpd)
  39. SERVICENAME="apache"
  40. ;;
  41. esac
  42. #############################
  43. # Action runner
  44. #############################
  45. case "$ACTION" in
  46. stop|start|restart|status)
  47. exec supervisorctl "$ACTION" "${SERVICENAME}:${SERVICENAME}d"
  48. ;;
  49. pid)
  50. echo $(getServicePid "${SERVICENAME}")
  51. ;;
  52. check)
  53. FIRST_PID=$(getServicePid "${SERVICENAME}")
  54. sleep 5
  55. SECOND_PID=$(getServicePid "${SERVICENAME}")
  56. if [[ "$FIRST_PID" == "$SECOND_PID" ]]; then
  57. echo "ok"
  58. exit 0
  59. else
  60. echo "not running"
  61. exit 1
  62. fi
  63. ;;
  64. *)
  65. echo "[ERROR] Invalid action"
  66. serviceHelp
  67. exit 1
  68. ;;
  69. esac