reverting back to original, pre-VM setup
[oweals/karmaworld.git] / fabfile.py
index 2ba37d334382c4a647d61f28fcf3699fd19e98da..01385adff043d5b6e3dbf756ca277b9dab243d5c 100644 (file)
-"""Management utilities."""
 
+""" Karmaworld Fabric management script
+    Finals Club (c) 2013"""
 
-from fabric.contrib.console import confirm
-from fabric.api import abort, env, local, settings, task
+import os
+import ConfigParser
 
+from fabric.api import cd, env, lcd, prefix, run, sudo, task, local, settings
+from fabric.contrib import files
 
-########## GLOBALS
-env.run = 'heroku run python manage.py'
-HEROKU_ADDONS = (
-    'cloudamqp:lemur',
-    'heroku-postgresql:dev',
-    'scheduler:standard',
-    'memcache:5mb',
-    'newrelic:standard',
-    'pgbackups:auto-month',
-    'sentry:developer',
-)
-HEROKU_CONFIGS = (
-    'DJANGO_SETTINGS_MODULE=karmaworld.settings.prod',
-    'SECRET_KEY=(s1k!&^7l28k&nrm2ek(qqo&19%y(zn#=^zq_*ur2@irjun0x4'
-    'AWS_ACCESS_KEY_ID=xxx',
-    'AWS_SECRET_ACCESS_KEY=xxx',
-    'AWS_STORAGE_BUCKET_NAME=xxx',
-)
-########## END GLOBALS
+######### GLOBAL
+env.user = 'vagrant'
+env.group = 'vagrant'
+env.proj_repo = 'git@github.com:FinalsClub/karmaworld.git'
+env.repo_root = '~/karmaworld'
+env.proj_root = '/var/www/karmaworld'
+env.branch = 'prod'
+env.code_root = '{0}/{1}-code'.format(env.proj_root, env.branch)
+env.supervisor_conf = '{0}/confs/{1}/supervisord.conf'.format(env.code_root, env.branch)
 
+######## Define host(s)
+def here():
+    """
+    Connection information for the local machine
+    """
+    def _custom_local(command):
+        prefixed_command = '/bin/bash -l -i -c "%s"' % command
+        return local(prefixed_command)
+
+    # This is required for the same reason as above
+    env.proj_root = '/var/www/karmaworld'
+    env.cd = lcd
+    env.reqs = 'reqs/dev.txt'
+    env.confs = 'confs/beta'
+    env.branch = 'beta'
 
-########## HELPERS
-def cont(cmd, message):
-    """Given a command, ``cmd``, and a message, ``message``, allow a user to
-    either continue or break execution if errors occur while executing ``cmd``.
 
-    :param str cmd: The command to execute on the local system.
-    :param str message: The message to display to the user on failure.
 
-    .. note::
-        ``message`` should be phrased in the form of a question, as if ``cmd``'s
-        execution fails, we'll ask the user to press 'y' or 'n' to continue or
-        cancel exeuction, respectively.
+####### Define production host
+@task
+def prod():
+    """
+    Connection Information for production machine
+    """
 
-    Usage::
+    env.user = 'djkarma'
+    env.hosts = ['karmanotes.org']
+    env.proj_root = '/var/www/karmaworld'
+    env.reqs = 'reqs/prod.txt'
+    env.confs = 'confs/prod/'
+    env.branch = 'beta'
+    env.gunicorn_addr = '127.0.0.1:8000'
 
-        cont('heroku run ...', "Couldn't complete %s. Continue anyway?" % cmd)
+####### Define beta host
+@task
+def beta():
+    """
+    Connection Information for beta machine
     """
-    with settings(warn_only=True):
-        result = local(cmd, capture=True)
 
-    if message and result.failed and not confirm(message):
-        abort('Stopped execution per user request.')
-########## END HELPERS
+    env.user = 'djkarma'
+    env.hosts = ['beta.karmanotes.org']
+    env.proj_root = '/var/www/karmaworld'
+    env.reqs = 'reqs/prod.txt'
+    env.confs = 'confs/prod/'
+    env.branch = 'beta'
+
+######## Run Commands in Virutal Environment
+def virtenv_exec(command):
+    """
+    Execute command in Virtualenv
+    """
 
+    path = os.path.sep.join( (env.proj_root, env.branch) )
+    with prefix('source {0}/bin/activate'.format(path)):
+        run(command)
 
-########## DATABASE MANAGEMENT
+######## Sync database
 @task
 def syncdb():
-    """Run a syncdb."""
-    local('%(run)s syncdb --noinput' % env)
+    """
+    Sync Database
+    """
+    virtenv_exec('{0}/manage.py syncdb --migrate'.format(env.code_root))
+
+
+####### Collect Static Files
+@task
+def collect_static():
+       """
+       Collect static files (if AWS config. present, push to S3)
+       """
 
+       virtenv_exec('%s/manage.py collectstatic --noinput' % env.proj_root )   
 
+####### Run Dev Server
 @task
-def migrate(app=None):
-    """Apply one (or more) migrations. If no app is specified, fabric will
-    attempt to run a site-wide migration.
+def dev_server():
+       """
+       Runs the built-in django webserver
+       """
+
+       virtenv_exec('%s/manage.py runserver' % env.proj_root)  
+
+####### Create Virtual Environment
+@task
+def make_virtualenv():
+       """
+       Create our Virtualenv in env.proj_root
+       """
+
+        path = os.path.sep.join( (env.proj_root, env.branch) )
+        if not files.exists(path):
+            run('virtualenv {0}'.format(path))
+        if not files.exists(env.code_root):
+            run('ln -s {0} {1}'.format(env.repo_root, env.code_root))
 
-    :param str app: Django app name to migrate.
+@task
+def start_supervisord():
+    """
+    Starts supervisord
     """
-    if app:
-        local('%s migrate %s --noinput' % (env.run, app))
-    else:
-        local('%(run)s migrate --noinput' % env)
-########## END DATABASE MANAGEMENT
+    virtenv_exec('supervisord -c {0}'.format(env.supervisor_conf))
 
 
-########## FILE MANAGEMENT
 @task
-def collectstatic():
-    """Collect all static files, and copy them to S3 for production usage."""
-    local('%(run)s collectstatic --noinput' % env)
-########## END FILE MANAGEMENT
+def stop_supervisord():
+    """
+    Restarts supervisord
+    """
+    virtenv_exec('supervisorctl -c {0} shutdown'.format(env.supervisor_conf))
 
 
-########## HEROKU MANAGEMENT
 @task
-def bootstrap():
-    """Bootstrap your new application with Heroku, preparing it for a production
-    deployment. This will:
+def restart_supervisord():
+    """
+    Restarts supervisord
+    """
+    stop_supervisord()
+    start_supervisord()
+
 
-        - Create a new Heroku application.
-        - Install all ``HEROKU_ADDONS``.
-        - Sync the database.
-        - Apply all database migrations.
-        - Initialize New Relic's monitoring add-on.
+def supervisorctl(action, process):
+    """
+    Takes as arguments the name of the process as is
+    defined in supervisord.conf and the action that should
+    be performed on it: start|stop|restart.
     """
-    cont('heroku create', "Couldn't create the Heroku app, continue anyway?")
+    virtenv_exec('supervisorctl -c {0} {1} {2}'.format(env.supervisor_conf, action, process))
 
-    for addon in HEROKU_ADDONS:
-        cont('heroku addons:add %s' % addon,
-            "Couldn't add %s to your Heroku app, continue anyway?" % addon)
 
-    for config in HEROKU_CONFIGS:
-        cont('heroku config:add %s' % config,
-            "Couldn't add %s to your Heroku app, continue anyway?" % config)
+@task
+def start_celeryd():
+    """
+    Starts the celeryd process
+    """
+    supervisorctl('start', 'celeryd')
 
-    cont('git push heroku master',
-            "Couldn't push your application to Heroku, continue anyway?")
 
-    syncdb()
-    migrate()
+@task
+def stop_celeryd():
+    """
+    Stops the celeryd process
+    """
+    supervisorctl('stop', 'celeryd')
+
+
+@task
+def restart_celery():
+    """
+    Restarts the celeryd process
+    """
+    supervisorctl('restart', 'celeryd')
+
+
+@task
+def start_gunicorn():
+    """
+    Starts the gunicorn process
+    """
+    supervisorctl('start', 'gunicorn')
+
+
+@task
+def stop_gunicorn():
+    """
+    Stops the gunicorn process
+    """
+    supervisorctl('stop', 'gunicorn')
+
+
+@task
+def restart_gunicorn():
+    """
+    Restarts the gunicorn process
+    """
+    supervisorctl('restart', 'gunicorn')
 
-    cont('%(run)s newrelic-admin validate-config - stdout' % env,
-            "Couldn't initialize New Relic, continue anyway?")
 
+####### Update Requirements
+@task
+def update_reqs():
+    virtenv_exec('pip install -r {0}/reqs/{1}.txt'.format(env.repo_root, env.branch))
 
+####### Pull new code
 @task
-def destroy():
-    """Destroy this Heroku application. Wipe it from existance.
+def update_code():
+    virtenv_exec('cd %s; git pull' % env.proj_root )
 
-    .. note::
-        This really will completely destroy your application. Think twice.
+def backup():
+    """
+    Create backup using bup
     """
-    local('heroku apps:destroy')
-########## END HEROKU MANAGEMENT
+    pass
+
+@task
+def file_setup():
+    """
+    Deploy expected files and directories from non-apt system services.
+    """
+    ini_parser = ConfigParser.SafeConfigParser()
+    if not ini_parser.read(env.supervisor_conf):
+      raise Exception("Could not parse INI file {0}".format(env.supervisor_conf))
+    for section, option in (('supervisord','logfile'),
+                            ('supervisord','pidfile'),
+                            ('unix_http_server','file'),
+                            ('program:celeryd','stdout_logfile')):
+      filepath = ini_parser.get(section, option)
+      # generate file's directory structure if needed
+      run('mkdir -p {0}'.format(os.path.split(filepath)[0]))
+      # touch a file and change ownership if needed
+      if 'log' in option and not files.exists(filepath):
+          sudo('touch {0}'.format(filepath))
+          sudo('chown {0}:{1} {2}'.format(env.user, env.group, filepath))
+
+@task
+def check_secrets():
+    """
+    Ensure secret files exist for syncdb to run.
+    """
+
+    secrets_path = env.code_root + '/karmaworld/secret'
+    secrets_files = ('filepicker.py', 'static_s3.py', 'db_settings.py')
+
+    errors = []
+    for sfile in secrets_files:
+        ffile = os.path.sep.join((secrets_path,sfile))
+        if not files.exists(ffile):
+            errors.append('{0} missing. Please add and try again.'.format(ffile))
+    if errors:
+        raise Exception('\n'.join(errors))
+
+@task
+def first_deploy():
+    """
+    Sets up and deploys the project for the first time.
+    """
+    make_virtualenv()
+    file_setup()
+    check_secrets()
+    update_reqs()
+    syncdb()
+    start_supervisord()
+
+
+@task
+def deploy():
+    """
+    Deploys the latest changes
+    """
+    update_code()
+    update_reqs()
+    syncdb()
+    collect_static()
+    restart_supervisord()
+########## END COMMANDS