Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: b495e17550
Fetching contributors…

Cannot retrieve contributors at this time

file 307 lines (242 sloc) 9.53 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
from datetime import datetime

from fabric.api import local, run, sudo, prefix, cd, env
from fabric.contrib import django
from fabric.contrib.files import upload_template, append, comment, uncomment
from fabric.contrib.console import confirm
from fabric.operations import get
from fabric import tasks
from fabric.utils import abort, puts

from django.conf import settings

django.settings_module('settings.development')
for attr in ['DOMAIN', 'USER', 'HOST', 'PASSWORD', 'REPO']:
    if not hasattr(settings, 'FABRIC_%s' % attr):
        abort('You must set FABRIC_%s in your settings file' % attr)

env.domain = settings.FABRIC_DOMAIN
env.user = settings.FABRIC_USER
env.hosts = [settings.FABRIC_HOST]
env.password = settings.FABRIC_PASSWORD
env.repo = settings.FABRIC_REPO

env.path = local('pwd')
# Allow fabric to restart apache2
env.always_use_pty = False

# Number of previous deploy releases to keep
RELEASE_COUNT = getattr(settings, 'FABRIC_RELEASES', 5)


class BaseTask(tasks.Task):

    def run(self):
        if not hasattr(env, 'name'):
            abort('You must specify an environment to deploy to\n\n'\
                  'e.g. fab production prepare_environment')

    def get_local_settings(self):
        django.settings_module('settings.development')
        return settings

    def select_env(self, name='staging'):
        env.name = name
        env.virtual_env = '$WORKON_HOME/%(domain)s' % env
        django.settings_module('settings.%(name)s' % env)


class Production(BaseTask):
    """
Run tasks in production environment
"""
    name = 'production'

    def run(self):
        env.repo = env.domain.replace('.', '_')
        return self.select_env('production')


class Staging(BaseTask):
    """
Run tasks in staging environment
"""
    name = 'staging'

    def run(self):
        env.repo = env.domain.replace('.', '_')
        env.domain = 'staging.%(domain)s' % env
        return self.select_env('staging')


class Bootstrap(BaseTask):
    """
Prepare a virtualenv with apache2 and nginx config files
"""
    name = 'bootstrap'

    def run(self):
        super(Bootstrap, self).run()
        self.create_virtualenv()
        self.clone_git_repo()
        self.create_folders()
        self.upload_config_files()

    def create_virtualenv(self):
        sudo('chmod 777 $WORKON_HOME/hook.log')
        run('mkvirtualenv %(domain)s' % env)
        # append env vars to virtualenv activate file
        append('%(virtual_env)s/bin/activate' % env, ['',
            'export DJANGO_SETTINGS_MODULE=settings.%(name)s' % env,
            'export PYTHONPATH=$VIRTUAL_ENV/project',
            ''])

    def clone_git_repo(self):
        # Checkout git repo from cahoona VM-3
        run('mkdir -p %(virtual_env)s/releases' % env)
        with cd('%(virtual_env)s/releases' % env):
            run('git clone %(repo)s current' % env)
        # symlink project to current release
        run('ln -s %(virtual_env)s/releases/current %(virtual_env)s/project'\
            % env)

    def create_folders(self):
        vhost = '/var/www/vhosts/%(domain)s/' % env
        run('mkdir %s' % vhost)
        with cd(vhost):
            run('mkdir -p {media,static,apache,log}')
            run('chmod 777 {media,log}')

    def upload_config_files(self):
        vhost_root = '/var/www/vhosts/%(domain)s' % env
        kwargs = dict(context=env, use_sudo=True, backup=False)
        # wsgi
        upload_template('%(real_fabfile)s/conf/wsgi.conf' % env,\
                        vhost_root + '/apache/%(name)s.wsgi' % env, **kwargs)
        # apache
        upload_template('%(real_fabfile)s/conf/apache.conf' % env,\
                    '/etc/apache2/sites-available/%(domain)s' % env, **kwargs)
        sudo('a2ensite %(domain)s' % env)
        sudo('service apache2 restart')

        # nginx
        upload_template('%(real_fabfile)s/conf/nginx.conf' % env,\
                    '/etc/nginx/sites-available/%(domain)s' % env, **kwargs)
        sudo('ln -sf /etc/nginx/sites-available/%(domain)s '\
             '/etc/nginx/sites-enabled/%(domain)s' % env)
        sudo('service nginx restart')


class BaseDeploy(BaseTask):

    def update_and_migrate(self):
        with cd('%(virtual_env)s/project' % env):
            with prefix('workon %(domain)s' % env):
                run('pip install -r REQUIREMENTS')
                run('django-admin.py migrate --all')
                run('django-admin.py collectstatic --noinput')

    def remove_old_releases(self):
        with cd('%(virtual_env)s/releases' % env):
            # Tidy up (remove) old releases
            while int(run('ls -1 | wc -l')) > RELEASE_COUNT:
                run('rm -Rf $(ls . | sort -f | head -n 1)')


class Deploy(BaseDeploy):
    """
Deploy project to remote server
"""
    name = 'deploy'

    def run(self):
        super(Deploy, self).run()
        sudo('chmod 777 $WORKON_HOME/hook.log')

        # Move current to old release
        with cd('%(virtual_env)s/releases' % env):
            now = datetime.now().strftime('%Y%m%d%H%M%S')
            run('cp -R current %s' % now)

        with cd('%(virtual_env)s/project' % env):
            run('git pull')

        self.remove_old_releases()
        self.update_and_migrate()
        sudo('service apache2 graceful')


class Rollback(BaseDeploy):
    """
Rollback remote project to previous release if one exists
"""
    name = 'rollback'

    def run(self, update_requirements=True, migrate=True, static=True):
        super(Rollback, self).run()
        with cd('%(virtual_env)s/releases' % env):
            # Only rollback if we have previous releases
            if int(run('ls -1 | wc -l')) < 2:
                abort('There is no previous release to rollback to')

            # Get previous release
            output = run("ls . | sort -f | grep -v '^current$' $1")
            previous_release = output.split()[-1]

            # Move previous release to current
            run('rm -Rf current')
            run('mv %s current' % previous_release)

        self.remove_old_releases()
        self.update_and_migrate()
        sudo('service apache2 graceful')


class Test(tasks.Task):
    """
Run tests locally
"""
    name = 'test'

    def run(self):
        with prefix('source ../bin/activate'):
            with cd('$VIRTUAL_ENV/project'):
                local('django-admin.py validate')
                local('django-admin.py test')


class CreateDatabase(BaseTask):
    """
Create and populate remote database (with syncdb)
"""
    name = 'create_database'

    def run(self, run_migrations=False):
        remote_db_settings = {
            'USER': 'root',
            'PASSWORD': env.password,
            'NAME': env.domain.replace('.', '_')}

        sudo('mysql -u%(USER)s -p%(PASSWORD)s -e '\
             '"CREATE DATABASE %(NAME)s"' % remote_db_settings)
        with prefix('workon %(domain)s' % env):
            migs = ' --migrate' if run_migrations else ''
            run('django-admin.py syncdb --noinput %s' % migs)


class SyncLocalDatabase(BaseTask):
    """
Download database from remote server to local env
"""
    name = 'sync_local_database'

    def run(self):
        super(SyncLocalDatabase, self).run()
        dump = '/tmp/%(domain)s.json' % env
        # Remote
        with cd('%(virtual_env)s/project' % env):
            with prefix('workon %(domain)s' % env):
                run('django-admin.py dumpdata > %s --exclude=contenttypes' %\
                    dump)

        # Local
        with prefix('source ../bin/activate'):
            with cd('$VIRTUAL_ENV/project'):
                get(dump, '/tmp/')
                local('django-admin.py syncdb --noinput --migrate')
                local('django-admin.py flush --noinput')
                local('django-admin.py loaddata %s' % dump)


class SyncLocalMedia(BaseTask):
    """
Download media from remote server to local env
"""
    name = 'sync_local_media'

    def run(self):
        super(SyncLocalMedia, self).run()
        remote_dir = '/var/www/vhosts/%(domain)s/media' % env
        tar = '/tmp/%(domain)s.tar' % env

        # Remote
        with cd(remote_dir):
            run('tar -czf %s .' % tar)
        
        # Local
        get(tar, '/tmp')
        with prefix('source ../bin/activate'):
            local_settings = self.get_local_settings()
            local('mkdir -p %s' % local_settings.MEDIA_ROOT)
            local('chmod 777 %s' % local_settings.MEDIA_ROOT)
            with cd(local_settings.MEDIA_ROOT):
                local('tar -C %s -xvf %s' %\
                      (local_settings.MEDIA_ROOT, tar))

class VirtualenvPermission(tasks.Task):

    name = 'virtualenv_permission'

    def run(self):
        sudo('chmod 777 $WORKON_HOME/hook.log')


class RemoteDjangoAdmin(BaseTask):
    "Run django-admin.py commands remotely"
    name = 'django_admin'

    def run(self, cmd=None):
        super(RemoteDjangoAdmin, self).run()
        if cmd:
            with prefix('workon %(domain)s' % env):
                run('django-admin.py %s' % cmd)
        else:
            abort('You must specify a command (e.g. sycdb --migrate)')


virtualenv_permission = VirtualenvPermission()
production = Production()
staging = Staging()
bootstrap = Bootstrap()
deploy = Deploy()
rollback = Rollback()
test = Test()
create_database = CreateDatabase()
sync_local_database = SyncLocalDatabase()
sync_local_media = SyncLocalMedia()
django_admin = RemoteDjangoAdmin()
Something went wrong with that request. Please try again.