2 Generic fabric deployment script.
 
   3 Create a fabfile.py in the project and start it with:
 
   5     from fnpdeploy import *
 
   7 Then set up some env properties:
 
   8     project_name: slug-like project name
 
   9     hosts: list of target host names
 
  10     user: remote user name
 
  11     app_path: where does the app go
 
  12     services: list of tasks to run after deployment
 
  13     django_root_path (optional): path to the directory
 
  14         containing django project, relative to the
 
  15         root of the repository (defaults to '.')
 
  16     localsettings_dst_path (optional): path indicating
 
  17         where to copy the localsettings file, relative
 
  18         to django_root_path (defaults to project_name/localsettings.py)
 
  19     migrate_fake (optional): list of (app, migration) pairs to fake-migrate
 
  20     skip_collect_static (optional): if True, Django collectstatic command is not called
 
  22 from subprocess import check_output
 
  23 from os.path import abspath, dirname, exists, join
 
  24 from fabric.api import *
 
  25 from fabric.context_managers import settings
 
  26 from fabric.contrib import files
 
  27 from fabric.tasks import Task, execute
 
  29 env.virtualenv = '/usr/bin/virtualenv'
 
  33 def get_random_string(length=12,
 
  34                       allowed_chars='abcdefghijklmnopqrstuvwxyz'
 
  35                                     'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
 
  36     from random import SystemRandom
 
  37     random = SystemRandom()
 
  38     return ''.join(random.choice(allowed_chars) for i in range(length))
 
  44     Setup all needed directories.
 
  46     require('hosts', 'app_path')
 
  48     if not files.exists(env.app_path):
 
  49         run('mkdir -p %(app_path)s' % env, pty=True)
 
  50     with cd(env.app_path):
 
  51         for subdir in 'releases', 'packages', 'log', 'samples':
 
  52             if not files.exists(subdir):
 
  53                 run('mkdir -p %s' % subdir, pty=True)
 
  54         # Install helper manage.py script into root dir.
 
  55         if not files.exists('manage.py'):
 
  56             with settings(full_django_root=get_django_root_path('current')):
 
  57                 upload_sample('manage.py', where='', ext='', mode=0755)
 
  58     with cd('%(app_path)s/releases' % env):
 
  59         if not files.exists('current'):
 
  60             run('ln -sfT . current', pty=True)
 
  61         if not files.exists('previous'):
 
  62             run('ln -sfT . previous', pty=True)
 
  67 def check_localsettings():
 
  68     return files.exists('%(app_path)s/localsettings.py' % env)
 
  74     Deploy the latest version of the site to the servers,
 
  75     install any required third party modules,
 
  76     install the virtual host and then restart the webserver
 
  78     require('hosts', 'app_path')
 
  81     env.release = '%s_%s' % (time.strftime('%Y-%m-%dT%H%M'), check_output(['git', 'rev-parse', 'HEAD']).strip())
 
  84     if not check_localsettings():
 
  85         abort('Setup is complete, but\n    %(app_path)s/localsettings.py\n'
 
  86               'is needed for actual deployment.' % env)
 
  89     install_requirements()
 
  90     symlink_current_release()
 
  99     Limited rollback capability. Simple loads the previously current
 
 100     version of the code. Rolling back again will swap between the two.
 
 101     Warning: this will almost certainly go wrong, it there were any migrations
 
 104     require('hosts', 'app_path')
 
 106         run('mv releases/current releases/_previous;', pty=True)
 
 107         run('mv releases/previous releases/current;', pty=True)
 
 108         run('mv releases/_previous releases/previous;', pty=True)
 
 113 def deploy_version(version):
 
 115     Loads the specified version.
 
 116     Warning: this will almost certainly go wrong, it there were any migrations
 
 119     "Specify a specific version to be made live"
 
 120     require('hosts', 'app_path')
 
 121     env.version = version
 
 123         run('rm releases/previous; mv releases/current releases/previous;', pty=True)
 
 124         run('ln -s %(version)s releases/current' % env, pty=True)
 
 130     for service in env.services or ():
 
 134 # =====================================================================
 
 135 # = Helpers. These are called by other functions rather than directly =
 
 136 # =====================================================================
 
 139     def upload_sample(self):
 
 142 class DebianGunicorn(Service):
 
 143     def __init__(self, name):
 
 144         super(Task, self).__init__()
 
 148         print '>>> restart webserver using gunicorn-debian'
 
 149         sudo('gunicorn-debian restart %s' % self.name, shell=False)
 
 151     def upload_sample(self):
 
 152         with settings(full_django_root=get_django_root_path('current')):
 
 153             upload_sample('gunicorn')
 
 155 class Apache(Service):
 
 157         print '>>> restart webserver by touching WSGI'
 
 159             run('touch %(app_path)s/%(project_name)s/wsgi.py' % env)
 
 161 class Supervisord(Service):
 
 162     def __init__(self, name):
 
 163         super(Task, self).__init__()
 
 167         print '>>> supervisord: restart %s' % self.name
 
 168         sudo('supervisorctl restart %s' % self.name, shell=False)
 
 171     def __init__(self, commands, working_dir):
 
 172         if not hasattr(commands, '__iter__'):
 
 173             commands = [commands]
 
 174         self.name = 'Command: %s @ %s' % (commands, working_dir)
 
 175         self.commands = commands
 
 176         self.working_dir = working_dir
 
 180         with cd(join('%(app_path)s/releases/current' % env, self.working_dir)):
 
 181             for command in self.commands:
 
 184 def upload_samples():
 
 185     upload_localsettings_sample()
 
 186     upload_nginx_sample()
 
 187     for service in env.services:
 
 188         service.upload_sample()
 
 190 def upload_sample(name, where="samples/", ext='.sample', **kwargs):
 
 191     require('app_path', 'project_name')
 
 192     upload_path = '%s/%s%s%s' % (env['app_path'], where, name, ext)
 
 193     if files.exists(upload_path):
 
 195     print '>>> upload %s template' % name
 
 196     template = '%(project_name)s/' % env + name + '.template'
 
 197     if not exists(template):
 
 198         template = join(dirname(abspath(__file__)), 'templates/' + name + '.template')
 
 199     files.upload_template(template, upload_path, env, **kwargs)
 
 201 def upload_localsettings_sample():
 
 202     "Fill out localsettings template and upload as a sample."
 
 203     env.secret_key = get_random_string(50)
 
 204     upload_sample('localsettings.py', where="")
 
 206 upload_nginx_sample = lambda: upload_sample('nginx')
 
 208 def upload_tar_from_git():
 
 209     "Create an archive from the current Git branch and upload it"
 
 210     print '>>> upload tar from git'
 
 211     require('release', provided_by=[deploy])
 
 213     local('git-archive-all.sh --format tar %(release)s.tar' % env)
 
 214     local('gzip %(release)s.tar' % env)
 
 215     run('mkdir -p %(app_path)s/releases/%(release)s' % env, pty=True)
 
 216     run('mkdir -p %(app_path)s/packages' % env, pty=True)
 
 217     put('%(release)s.tar.gz' % env, '%(app_path)s/packages/' % env)
 
 218     run('cd %(app_path)s/releases/%(release)s && tar zxf ../../packages/%(release)s.tar.gz' % env, pty=True)
 
 219     local('rm %(release)s.tar.gz' % env)
 
 221 def install_requirements():
 
 222     "Install the required packages from the requirements file using pip"
 
 223     print '>>> install requirements'
 
 224     require('release', provided_by=[deploy])
 
 227     if not files.exists(env.ve):
 
 229         require('virtualenv')
 
 230         run('%(virtualenv)s %(ve)s' % env, pty=True)
 
 231     with cd('%(app_path)s/releases/%(release)s' % env):
 
 232         run('%(ve)s/bin/pip install -r %(reqs)s' % {'ve': env.ve, 'reqs': env.get('requirements_file', 'requirements.txt')}, pty=True)
 
 233     with cd(get_django_root_path(env['release'])):
 
 234         # Install DB requirement
 
 236             'django.db.backends.postgresql_psycopg2': 'psycopg2',
 
 237             'django.db.backends.mysql': 'MySQL-python',
 
 240             'DJANGO_SETTINGS_MODULE=%(project_name)s.settings '
 
 241             '%(ve)s/bin/python -c \''
 
 242             'from django.conf import settings;'
 
 243             'print(" ".join(set([d["ENGINE"] for d in settings.DATABASES.values()])))\'' % env)
 
 244         for database in databases.split():
 
 245             if database in database_reqs:
 
 246                 # TODO: set pip default pypi
 
 247                 run('%(ve)s/bin/pip install ' % env + database_reqs[database])
 
 250 def copy_localsettings():
 
 251     "Copy localsettings.py from root directory to release directory (if this file exists)"
 
 252     print ">>> copy localsettings"
 
 253     require('release', provided_by=[deploy])
 
 254     require('app_path', 'project_name')
 
 256     with settings(warn_only=True):
 
 257         copy_to = join(get_django_root_path(env['release']), env.get('localsettings_dst_path', env['project_name']))
 
 258         run('cp %(app_path)s/localsettings.py ' % env + copy_to)
 
 260 def symlink_current_release():
 
 261     "Symlink our current release"
 
 262     print '>>> symlink current release'
 
 263     require('release', provided_by=[deploy])
 
 265     with cd(env.app_path):
 
 266         run('rm releases/previous; mv releases/current releases/previous')
 
 267         run('ln -s %(release)s releases/current' % env)
 
 270     "Update the database"
 
 272     require('app_path', 'project_name')
 
 273     with cd(get_django_root_path('current')):
 
 274         run('%(ve)s/bin/python manage.py syncdb --noinput' % env, pty=True)
 
 275         for app, migration in env.get('migrate_fake', ()):
 
 276             run('%s/bin/python manage.py migrate %s --fake %s' % (env.ve, app, migration), pty=True)
 
 277         run('%(ve)s/bin/python manage.py migrate' % env, pty=True)
 
 279 def pre_collectstatic():
 
 280     print '>>> pre_collectstatic'
 
 281     for task in env.get('pre_collectstatic', []):
 
 285     """Collect static files"""
 
 286     print '>>> collectstatic'
 
 287     if env.get('skip_collect_static', False):
 
 290     require('app_path', 'project_name')
 
 291     with cd(get_django_root_path('current')):
 
 292         run('%(ve)s/bin/python manage.py collectstatic --noinput' % env, pty=True)
 
 294 def get_django_root_path(release):
 
 296     path = '%(app_path)s/releases/%(release)s' % dict(app_path = env['app_path'], release = release)
 
 297     if 'django_root_path' in env:
 
 298         path = join(path, env['django_root_path'])
 
 303         env['ve'] = '%s/ve' % env.app_path