Commits

sodas tsai committed c045fe9

Use 'apache' user to run beanstalk commands at /var/beanstalk

Comments (0)

Files changed (6)

beanstalk/__init__.py

 
 # Pacakge information
 #-----------------------------------------------------------------------------------------------------------------------
-__version__ = '0.1.70'
+__version__ = '0.1.74'
 VERSION = tuple(map(lambda x: int(x), __version__.split('.')))
 BEANSTALK_ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
 

beanstalk/default_settings/server_settings.py

 BEANSTALK_STACK_BASE = '/var/beanstalk'
 STATIC_URL_PREFIX = 'static'
 BEANSTALK_EMAIL = 'beanstalk@beanstalk-stack.com'
+UWSGI_COMMAND = '/usr/local/bin/uwsgi'
+RUN_LOCATION = '/var/run/beanstalk'
 
+# Hooked Actions
+#-----------------------------------------------------------------------------------------------------------------------
 PRE_SETUP_ACTIONS = []  # Only beanstalk settings
 POST_SETUP_ACTIONS = []  # Only beanstalk settings
 

beanstalk/static/beanstalk_init.sh

 # Description:       starts beanstalk app server using start-stop-daemon
 ### END INIT INFO
 
-. /etc/rc.d/init.d/functions
-
-PROG=beanstalk-stack
-DAEMON=/usr/local/bin/uwsgi
-CONFIG=/etc/beanstalk/uwsgi.ini
-RUN=/var/run/beanstalk
-PID=${RUN}/uwsgi.pid
-ARGS="--ini ${CONFIG} --log-syslog=uwsgi --pidfile=${PID}"
-
-function start() {
-    echo -n "Starting ${PROG}:"
-    if [[ -f ${PID} ]]; then
-        ${MOVE_TO_COL}
-        echo -e "[\033[31mFAILED\033[0m]"
-        echo "${PROG} has been already started."
-        return 1
-    else
-        ${DAEMON} ${ARGS} 1>/dev/null 2>&1
-        OUT=$?
-        if [ ${OUT} -eq 0 ];then
-            ${MOVE_TO_COL}
-            echo -e "[\033[32m  OK  \033[0m]"
-        else
-            ${MOVE_TO_COL}
-            echo -e "[\033[31mFAILED\033[0m]"
-        fi
-    fi
-    return 0
-}
-
-function stop() {
-    echo -n "Stopping ${PROG}:"
-    if [[ -f ${PID} ]]; then
-        ${DAEMON} --stop ${PID}
-        rm -rf ${PID}
-        ${MOVE_TO_COL}
-        echo -e "[\033[32m  OK  \033[0m]"
-    else
-        ${MOVE_TO_COL}
-        echo -e "[\033[31mFAILED\033[0m]"
-        echo "${PROG} has been already stopped."
-        return 1
-    fi
-    return 0
-}
-
 case "$1" in
-    start)
-        start
+    start|stop|reload|restart)
+        bsjack daemon.$1
         OUT=$?
-        if [ ${OUT} != 0 ]; then
-            exit ${OUT}
-        fi
-        ;;
-    stop)
-        stop
-        OUT=$?
-        if [ ${OUT} != 0 ]; then
-            exit ${OUT}
-        fi
-        ;;
-    reload)
-        echo "Reloading ${PROG} conf"
-        if [[ -f ${PID} ]]; then
-            ${DAEMON} --reload ${PID}
-        fi
-        ;;
-    restart)
-        echo "Restart ${PROG}"
-        stop
-        start
+        exit ${OUT}
         ;;
     *)
-        echo "Usage: $0 {start|stop|reload|restart}"
+        bsjack daemon.usage
         exit 1
     ;;
 esac
-
-exit 0

beanstalk/tasks/__init__.py

 from fabric.api import task
-from beanstalk.tasks import app, server, users, info, utils
+from beanstalk.tasks import app, server, users, info, utils, daemon
 
 
 settings = task(alias='settings')(utils.load_role_settings)

beanstalk/tasks/daemon.py

+import os
+import sys
+from fabric.api import *
+from fabric.colors import *
+from beanstalk import BEANSTALK_GLOBAL_BASE_PATH
+from beanstalk.decorators import beanstalk_role
+from beanstalk.tasks.utils import load_role_settings
+
+_screen_width = 67
+
+
+def _result(success, hint):
+    spaces = (_screen_width - len(hint) - 8)
+    status = green('  OK  ') if success else red('FALIED')
+    return ' ' * spaces + '[{status}]'.format(status=status)
+
+
+@task
+@beanstalk_role('server')
+@with_settings(hide('running', 'status'))
+def start():
+    hint = 'Start beanstalk:'
+    sys.stdout.write(hint)
+
+    beanstalk_settings = load_role_settings()
+
+    pid_file = os.path.join(beanstalk_settings['RUN_LOCATION'], 'uwsgi.pid')
+
+    arg_context = {
+        'config_file': os.path.join(BEANSTALK_GLOBAL_BASE_PATH, 'uwsgi.ini'),
+        'pid_file': pid_file,
+    }
+    command_context = {
+        'command': beanstalk_settings['UWSGI_COMMAND'],
+        'args': '--ini {config_file} --log-syslog=uwsgi --pidfile={pid_file}'.format(**arg_context),
+    }
+
+    if not os.path.exists(pid_file):
+        with lcd(beanstalk_settings['BEANSTALK_STACK_BASE']):
+            result = local('{command} {args} 1>/dev/null 2>&1'.format(**command_context))
+        sys.stdout.write(_result(result.succeeded, hint))
+    else:
+        sys.stdout.write(_result(False, hint))
+        sys.stdout.write('\nBeanstalk-stack has been already started.')
+
+    sys.stdout.write('\n')
+
+
+@task
+@beanstalk_role('server')
+@with_settings(hide('running', 'status'))
+def stop():
+    hint = 'Stop beanstalk:'
+    sys.stdout.write(hint)
+
+    beanstalk_settings = load_role_settings()
+
+    pid_file = os.path.join(beanstalk_settings['RUN_LOCATION'], 'uwsgi.pid')
+
+    command_context = {
+        'command': beanstalk_settings['UWSGI_COMMAND'],
+        'args': '--stop {pid_file}'.format(pid_file=pid_file),
+    }
+
+    if not os.path.exists(pid_file):
+        sys.stdout.write(_result(False, hint))
+        sys.stdout.write('\nBeanstalk-stack has been already stopped.')
+    else:
+        result = local('{command} {args} 1>/dev/null 2>&1'.format(**command_context))
+        if result.succeeded:
+            local('rm -rf {pid_file}'.format(pid_file=pid_file))
+        sys.stdout.write(_result(result.succeeded, hint))
+
+    sys.stdout.write('\n')
+
+
+@task
+@beanstalk_role('server')
+@with_settings(hide('running', 'status'))
+def reload():
+    hint = 'Reload beanstalk:'
+    sys.stdout.write(hint)
+
+    beanstalk_settings = load_role_settings()
+
+    pid_file = os.path.join(beanstalk_settings['RUN_LOCATION'], 'uwsgi.pid')
+
+    command_context = {
+        'command': beanstalk_settings['UWSGI_COMMAND'],
+        'args': '--reload {pid_file}'.format(pid_file=pid_file),
+    }
+
+    if os.path.exists(pid_file):
+        result = local('{command} {args} 1>/dev/null 2>&1'.format(**command_context))
+        sys.stdout.write(_result(result.succeeded, hint))
+
+    sys.stdout.write('\n')
+
+
+@task
+@beanstalk_role('server')
+@with_settings(hide('running', 'status'))
+def restart():
+    print 'Restarting beanstalk-stack:'
+    with settings(hide('warnings', 'status', 'running'), warn_only=True):
+        execute(stop)
+        execute(start)
+
+
+@task
+@with_settings(hide('running', 'status'))
+def usage():
+    print 'Usage: {start|stop|reload|restart}'

beanstalk/tasks/server.py

 from fabric.contrib.console import confirm
 from ground_soil.fabric import eval_kwargs, virtual_env
 from ground_soil.filesystem import temporary_directory, render_file, sed
-from beanstalk import IDENTIFIER, BEANSTALK_ROOT_PATH
+from beanstalk import IDENTIFIER, BEANSTALK_ROOT_PATH, BEANSTALK_GLOBAL_BASE_PATH
 from beanstalk.decorators import beanstalk_role
 from beanstalk.paths.server import (project_base_path, project_source_path, project_logs_path, project_venv_path,
                                     project_uwsgi_path, apache_conf_path, app_ports_path)
     local('chmod o+rx %s' % beanstalk_stack_base)
 
     # Global ini
-    local('mkdir -p /etc/beanstalk')
-    if not os.path.exists('/etc/beanstalk/uwsgi.ini'):
+    local('mkdir -p {0}'.format(BEANSTALK_GLOBAL_BASE_PATH))
+    global_uwsgi_ini_path = os.path.join(BEANSTALK_GLOBAL_BASE_PATH, 'uwsgi.ini')
+    if not os.path.exists(global_uwsgi_ini_path):
         print section_title('Create global settings')
         global_uwsgi_ini_template_path = os.path.join(BEANSTALK_ROOT_PATH, 'static/global_uwsgi.ini')
         with hide('everything'):
-            uid = local('id -u beanstalk', capture=True)
+            uid = local('id -u apache', capture=True)
         global_uwsgi_ini_content = render_file(global_uwsgi_ini_template_path, beanstalk_settings, BEANSTALK_UID=uid)
-        with open('/etc/beanstalk/uwsgi.ini', 'w') as f:
+        with open(global_uwsgi_ini_path, 'w') as f:
             f.write(global_uwsgi_ini_content)
 
     # Apache command
     # edit ini
     uwsgi_path = project_uwsgi_path(project_name)
     config = ConfigParser.ConfigParser()
+    # load in if it exists
     if os.path.exists(uwsgi_path):
         config.read(uwsgi_path)
+    # Create uwsgi section
     if not config.has_section('uwsgi'):
         config.add_section('uwsgi')
+    # Options that user can define
     optional_overrride_options = [
         ('master', True),
         ('enable-threads', True),
     for key, value in optional_overrride_options:
         if not config.has_option('uwsgi', key):
             config.set('uwsgi', key, value)
+    # Options that must be overriden by beanstalk
     must_override_options = [
         ('socket', '127.0.0.1:%d' % uwsgi_port),
         ('chdir', project_source_path(project_name)),
         ('home', project_venv_path(project_name)),
+        ('logto', os.path.join(project_logs_path(project_name), 'uwsgi.log')),
     ]
     for key, value in must_override_options:
         config.set('uwsgi', key, value)
-    with hide('everything'):
-        uid = local('id -u beanstalk', capture=True)
-    config.set('uwsgi', 'uid', uid)
-    config.set('uwsgi', 'logto', os.path.join(project_logs_path(project_name), 'uwsgi.log'))
-    config.remove_option('uwsgi', 'http')
-    config.remove_option('uwsgi', 'https')
-    config.remove_option('uwsgi', 'http-proxy')
-    config.remove_option('uwsgi', 'http-to')
+    # Remove options
+    must_remove_options = [
+        'uid',
+        'http',
+        'https',
+        'http-proxy',
+        'http-to',
+    ]
+    for key in must_remove_options:
+        config.remove_option('uwsgi', key)
+    # Write it back
     with open(uwsgi_path, 'wb') as f:
         config.write(f)