Skip to content

Raspberry Pi nginx init

David Genord II edited this page Nov 20, 2015 · 1 revision
#!/bin/sh

### BEGIN INIT INFO
# Provides:           nginx
# Required-Start:     $local_fs $remote_fs $network $syslog $named
# Required-Stop:      $local_fs $remote_fs $network $syslog $named
# Default-Start:      2 3 4 5
# Default-Stop:       0 1 6
# Short-Description:  nginx LSB init script
# Description:        nginx Linux Standards Base compliant init script.
### END INIT INFO

# ----------------------------------------------------------------------------------------------------------------------
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form
# or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.
#
# In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright
# interest in the software to the public domain. We make this dedication for the benefit of the public at large and to
# the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in
# perpetuity of all present and future rights to this software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <http://unlicense.org>
# ----------------------------------------------------------------------------------------------------------------------

# ----------------------------------------------------------------------------------------------------------------------
# nginx Linux Standards Base compliant SysVinit script.
#
# SEE: https://wiki.debian.org/LSBInitScripts
# SEE: http://paste.ubuntu.com/6918156/
# SEE: http://tldp.org/LDP/abs/html/exitcodes.html
#
# IDEAS BY:   Karl Blessing <http://kbeezie.com/debian-ubuntu-nginx-init-script/>
# AUTHOR:     Richard Fussenegger <[email protected]>
# COPYRIGHT:  2013-15 Richard Fussenegger
# LICENSE:    http://unlicense.org/ PD
# LINK:       http://richard.fussenegger.info/
# ----------------------------------------------------------------------------------------------------------------------


# ----------------------------------------------------------------------------------------------------------------------
#                                                                                                              Variables
# ----------------------------------------------------------------------------------------------------------------------


# The name of the daemon.
readonly NAME=nginx

# Arguments that should be passed to the executable.
DAEMON_ARGS=

# Absolute path to the printf executable.
readonly PRINT=/usr/bin/printf

# The path in which to search for the daemon.
readonly PATH=/opt/nginx/sbin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# Absolute path to the PID file.
PIDFILE=$(printf -- '%s/run/%s.pid' "$([ -d /run ] || printf -- /var)" "${NAME}")

# Will be set by /lib/init/vars.sh
VERBOSE=no

# Absolute path to the which executable.
readonly WHICH=/usr/bin/which


# ----------------------------------------------------------------------------------------------------------------------
#                                                                                                            Error Codes
#
# SEE: http://refspecs.linuxfoundation.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
# ----------------------------------------------------------------------------------------------------------------------


readonly EC_INVALID_ARGUMENT=2
readonly EC_SUPER_USER_ONLY=4
readonly EC_DAEMON_NOT_FOUND=5
readonly EC_RELOADING_FAILED=95
readonly EC_RESTART_STOP_FAILED=96
readonly EC_RESTART_START_FAILED=97
readonly EC_START_FAILED=98
readonly EC_STOP_FAILED=99


# ----------------------------------------------------------------------------------------------------------------------
#                                                                                                              Functions
# ----------------------------------------------------------------------------------------------------------------------


# Exit the script with an error code.
die()
{
    log_end_msg $1
    exit $1
}

# End the script.
end()
{
    [ "${VERBOSE}" != no ] && log_end_msg 0
    exit 0
}

# Display failure message.
fail()
{
    log_failure_msg "${NAME}" "$1"
}

# Display informational message.
info()
{
    [ "${VERBOSE}" != no ] && log_daemon_msg "${NAME}" "$1"
}

# Display success message.
ok()
{
    [ "${VERBOSE}" != no ] && log_success_msg "${NAME}" "$1"
}

# Display warning message.
warn()
{
    log_warning_msg "${NAME}" "$1"
}

# Print usage string.
usage()
{
    "${PRINT}" 'Usage: %s {start|stop|restart|try-restart|reload|force-reload|status}\n' "$0"
}

###
# Check privileges of caller. This will automatically exit if the caller has insufficient privileges.
#
# RETURN:
#   0 - sufficient privileges
###
check_privileges()
{
    if [ $(id -u) -ne 0 ]
    then
        fail 'super user only!'
        die ${EC_SUPER_USER_ONLY}
    fi
}

###
# Reloads the service.
#
# RETURN:
#   0 - successfully reloaded
#   1 - reloading failed
###
reload_service()
{
    start-stop-daemon --stop --signal HUP ${SSD_OPTIONS}
}

###
# Starts the service.
#
# RETURN:
#   0 - successfully started
#   1 - starting failed
###
start_service()
{
    start-stop-daemon --start ${SSD_OPTIONS} -- ${DAEMON_ARGS}
}

###
# Stops the service.
#
# RETURN:
#   0 - successfully stopped
#   1 - stopping failed
###
stop_service()
{
    start-stop-daemon --stop --signal QUIT --retry=TERM/30/KILL/5 ${SSD_OPTIONS}
}


# ----------------------------------------------------------------------------------------------------------------------
#                                                                                                               Includes
# ----------------------------------------------------------------------------------------------------------------------


# Load the VERBOSE setting and other rcS variables plus any script defaults.
for INCLUDE in /lib/init/vars.sh /etc/default/${NAME}
    do [ -r "${INCLUDE}" ] && . "${INCLUDE}"
done

# Make all variables which are allowed to be altered by the defaults file as read-only.
readonly DAEMON_ARGS
readonly PIDFILE


# ----------------------------------------------------------------------------------------------------------------------
#                                                                                                              Bootstrap
# ----------------------------------------------------------------------------------------------------------------------


# Load the LSB log_* functions.
INCLUDE=/lib/lsb/init-functions
if [ -r "${INCLUDE}" ]
then
    . "${INCLUDE}"
else
    "${PRINT}" '%s: unable to load LSB functions, cannot start service.\n' "${NAME}" 1>&2
    exit ${EC_DAEMON_NOT_FOUND}
fi

# Make sure only one argument was passed to the script.
if [ $# -ne 1 ]
then
    if [ $# -lt 1 -o "$1" = '' ]
        then fail 'action not specified.'
        else fail 'too many arguments.'
    fi
    usage 1>&2
    die ${EC_INVALID_ARGUMENT}
fi
readonly ACTION="$1"

# Check if daemon is a recognized program and get absolute path.
readonly DAEMON=$("${WHICH}" "${NAME}")
if [ ! -x "${DAEMON}" ]
then
    if [ "${ACTION}" = 'stop' ]
    then
        warn 'executable not found: stop request ignored'
        end
    else
        fail "executable not found: cannot ${ACTION} service"
        die ${EC_DAEMON_NOT_FOUND}
    fi
fi

# Default options for start-stop-daemon command.
readonly SSD_OPTIONS="--quiet --oknodo --pidfile "${PIDFILE}" --exec "${DAEMON}" --name "${NAME}""

# Determine the service's status.
#
#   0 = Program is running
#   1 = Program is not running and the PID file exists.
#   3 = Porgram is not running.
#   4 = Unable to determine status.
start-stop-daemon --status ${SSD_OPTIONS} 2>/dev/null 1>/dev/null
readonly STATUS=$?


# ----------------------------------------------------------------------------------------------------------------------
#                                                                                                           Handle Input
# ----------------------------------------------------------------------------------------------------------------------


case "$1" in

    # Reload the configuration, if the service is running, otherwise do nothing.
    force-reload|reload)
        if [ ${STATUS} -eq 0 ]
        then
            info 'reloading configuration ...'
            reload_service || die ${EC_RELOADING_FAILED}
        else
            info 'service not running, nothing to be done.'
        fi
    ;;

    # Restart the service, if the service is already running, otherwise start the service.
    restart)
        if [ ${STATUS} -eq 0 ]
        then
            info 'restarting service ...'
            stop_service || die ${EC_RESTART_STOP_FAILED}
            sleep 0.1
        fi
        start_service || die ${EC_RESTART_START_FAILED}
    ;;

    # Start the service, do nothing if it is already running.
    start)
        if [ ${STATUS} -eq 0 ]
        then
            ok 'already started.'
        else
            info 'starting ...'
            start_service || die ${EC_START_FAILED}
        fi
    ;;

    # Print service status.
    #
    # This can be invoked by any user and has different exit codes:
    #   0 - running and OK
    #   1 - dead and /var/run PID file exists
    #   2 - dead and /var/lock lock file exists
    #   3 - not running
    #   4 - unknown
    status)
        status_of_proc "${DAEMON}" "${NAME}" || exit $?
    ;;

    # Stop the service, do nothing if it is already stopped.
    stop)
        if [ ${STATUS} -eq 0 ]
        then
            info 'stopping ...'
            stop_service || die ${EC_STOP_FAILED}
        else
            info 'already stopped.'
        fi
    ;;

    # Restart the service, if the service is already running, otherwise do nothing.
    try-restart)
        check_privileges
        if [ ${STATUS} -eq 0 ]
        then
            info 'restarting service ...'
            stop_service || die ${EC_RESTART_STOP_FAILED}
            sleep 0.1
            start_service || die ${EC_RESTART_START_FAILED}
        else
            info 'service not running, nothing to be done.'
        fi
    ;;

    -h|--help)
        usage
    ;;

    *)
        fail "action '${ACTION}' not recognized."
        usage 1>&2
        exit ${EC_INVALID_ARGUMENT}
    ;;

esac

end
Clone this wiki locally