It's no secret that python is fantastic when it comes to rapid prototyping and development. When it comes to deploying a web application, the road to glory isn't as well paved and navigating the array of techniques and tools can be daunting.
This talk will address the advantages of continuous deployment, the success factors involved and the tools available, mainly focusing on experiences with Django web development.
3. Concepts from other talks
β The why
β Lean startups and customer discovery
β Do more with less
β The how
β EC2 / provisioning
β Architecture
β Developing for cloud deployment
β Monitoring live web applications
β IaaS vs PaaS
4. What is continuous delivery*
"Rapid, incremental, low-risk delivery of high quality, valuable
new functionality to users through automation of the build,
testing and deployment process" - Jez Humble
Deploying every good version of your software...
β¦ or at least being able to
"Minimising MTTBID (Mean Time to Bad Idea Detection)" β Etsy
* delivery == deployment for the purposes of this talk
5. More Than Technology
β Technology - For automation
β People - Cross-functional team, organised around
product
β Processes β Conventions and some glue that
technology can't automate
6. Why
β Fail fast, win fast - Build, Measure, Learn
β Competitive advantage
β Avoid YAGNI - do less
β Less manual process, less risk
β Real-time control
β Deploy on demand
β Decoupled deployment and release
β Self service environments
7. Continuous Delivery in Practice
β Single path to production
β Optimise for resilience
β Get comfortable with being uncomfortable
β Automate as much as possible
β If it hurts, do it more often
β Becomes natural, return on investment is fast/high
β Lots of ways to do it, here's what I've done...
8.
9. Develop Commit Build Stage Deploy Measure
Environments
β Make dev/test/prod as similar as possible
β Full stack, no "./manage.py runserver"
β Some exceptions make sense. eg for development:
β dummy email backend
β dummy message broker
β fewer threads/workers
β less memory
β less analytics instrumentation
10. Develop Commit Build Stage Deploy Measure
Environments
Dev/test virtualised using Vagrant
Create and configure lightweight, reproducible, and
portable development environments
$ vagrant up
$ vagrant ssh
12. Develop Commit Build Stage Deploy Measure
Environments
β Repeatable, versioned configuration
β Snowflake bad, phoenix good
β Puppet (masterless) for provisioning OS and services
β Fabric for scripted tasks, eg:
β copy database from production
β update requirements
β migrate database
β commit and push to repository
β Anti-pattern
β Can't spin up new environment with one command
13. Develop Commit Build Stage Deploy Measure
Development top level puppet config
include uwsgi
include statsd
include solr
include memcached
include rabbitmq Test configuration is the same
include nginx
include testing Production adds:
include arribaa backup
include arribaa::db_node monitoring
include arribaa::nginx
include arribaa::celery
14. Develop Commit Build Stage Deploy Measure
Using Fabric with Vagrant
def vagrant():
# get vagrant ssh setup
vagrant_config = _get_vagrant_config()
env.key_filename = vagrant_config['IdentityFile']
env.hosts = ['%s:%s' % (vagrant_config['HostName'],
vagrant_config['Port'])]
env.user = vagrant_config['User']
def _get_vagrant_config():
with lcd('../vagrant'):
result = local('vagrant ssh-config', capture=True)
conf = {}
for line in iter(result.splitlines()):
parts = line.split()
conf[parts[0]] = ' '.join(parts[1:])
return conf
Based on https://gist.github.com/1099132
15. Develop Commit Build Stage Deploy Measure
Dependencies
β virtualenv β separate env for each app
β pip β install dependencies into virtualenv
β use requirements file
β use explicit versions
β for repository based dependencies, use commit id
β or fork on github
16. Develop Commit Build Stage Deploy Measure
Dependencies
β Using virtualenv and pip with fabric
env.site_dir = '/opt/django-projects/arribaa'
env.app_dir = '/opt/django-projects/arribaa/arribaa'
env.pip_file = 'requirements.txt'
def ve_run(command, func=run, base_dir=env.app_dir, *args, **kwargs):
with cd(base_dir):
with prefix("source /opt/virtualenvs/%s/bin/activate" % env.virtualenv):
return func(command, *args, **kwargs)
def update_reqs():
ve_run('pip install -r %s' % env.pip_file, base_dir=env.site_dir)
17. Develop Commit Build Stage Deploy Measure
Database migration
β South
β Schema changes
β Data migrations
β Deploy separate expand and contract operations, eg:
β Expand
β add new column (update model, manage.py schemamigration β¦)
β map from old column (manage.py datamigration β¦)
β Deploy
β Contract (optional)
β remove old column ( update model, manage.py schemamigration β¦)
18. Develop Commit Build Stage Deploy Measure
Database migration
β Using South with fabric
def syncdb():
ve_run("python manage.py syncdb --noinput --migrate")
19. Develop Commit Build Stage Deploy Measure
Tying it all together
β Update pip requirements on vagrant VM
$ fab vagrant update_reqs
β Run data migration on vagrant VM
$ fab vagrant syncdb
20. Develop Commit Build Stage Deploy Measure
Source control
β Pick one, learn it
β Use tags to keep track of build status
β Avoid long-lived branches
β or integrate them β more overhead
β application code
β Tracks all code/documentation β deployment code
β provisioning code
β configuration code
β documentation
β not build artifacts
22. vagrant
βββ Vagrantfile Dev VM config
βββ puppet
βββ modules Puppet modules
β βββ arribaa
β βββ backup
β βββ graphite
β βββ ...
β βββ uwsgi
β βββ wget
βββ vagrant-manifests
βββ dev.pp Puppet dev
βββ prod.pp Puppet prod*
βββ test.pp Puppet test
* Not used by vagrant, but convenient to store here
24. Develop Commit Build Stage Deploy Measure
Test separation
β Split up tests by type
β Can parallelise, keeping test run times low
β < 20 minutes from commit to production
β Unit tests first, faster feedback
β Run tests on different triggers, keep some out of the main
build
β Etsy - Divide and Concur
β http://codeascraft.etsy.com/2011/04/20/divide-and-concur/
25. Develop Commit Build Stage Deploy Measure
Test separation
β Unit
β Functional/UI
β Selenium et al
β Staging and production smoke tests
β Crawl URLs
β Load/performance testing
β Flaky tests, Slow tests
β exclude from regular build, run on a separate schedule
26. Develop Commit Build Stage Deploy Measure
Test separation
β How to do this with Django?
β Suites
β Custom test runner
β Other test systems (Nose has an attrib plugin)
β My current solution
β Annotating tests, and adapted django-jenkins command
class TestBooking(TestCase):
@pipelineTag ("unit")
def test_when_lapsed(self):
oldbooking = factories.BookingFactory.build(when=some_old_date)
self.assertTrue(oldbooking.when_lapsed())
27. Develop Commit Build Stage Deploy Measure
Test separation
# Used to ignore tests
ignore = lambda test_item: None
def pipelineTag(*args):
"""
Let a testcase run if any of the tags are in sys.argv and
none of the tags match not-* in sys.argv.
"""
# Abstain if we're not in a build pipeline (ie using django-jenkins)
# or if no tag(s) specified
if 'jenkins_pipeline' not in sys.argv or not any(['tagged-' in arg for arg in sys.argv]):
return _id
tags = args
assert set(tags) < set(['unit', 'functional', 'flaky', 'slow', 'staging'])
#Silently ignore if no matching tag
if not any(['tagged-'+tag in sys.argv for tag in tags]):
return ignore
# Skip if "not-blah" tagged
if any(['not-'+tag in sys.argv for tag in tags]):
return skip('tagged: ' + ','.join([tag for tag in tags if 'not-'+tag in sys.argv]))
# This test made it through
return _id
28. Develop Commit Build Stage Deploy Measure
Build Pipeline
β One pipeline
β All developers feed start of pipeline via VCS (master)
β Improve policy of "don't deploy broken code"...
β ...with system where it's harder to deploy broken code
β Jenkins Build Pipeline Plugin
β Series of dependant jobs, each runs different tests
β Feeds into pre-deploy staging job
β Successful staging job enables deploy job
29. Develop Commit Build Stage Deploy Measure
Build Pipeline
Currently simple linear flow
31. Develop Commit Build Stage Deploy Measure
Staging/QA Job
β fab staging-deploy β very similar process to production deploy
β Test run of production deployment using Fabric
β Deploy code and config to staging environment (Vagrant VM)
β Apply dependency updates
β puppet config
β pip requirements
β Copy database from production and run data migration
β Should now have a deployed QA environment
β Browser smoke tests β currently selenium
β Not using Django 1.4 LiveTestCase here, we have a full stack to play with
β Tag successful build as deployable
32. Develop Commit Build Stage Deploy Measure
Deployment Strategies
β Optimistic
β Deploy, reload services β some appservers handle this well
β Blue/Green
β Parallel environments, 1 idle
β Idle environment gets new version
β Smoke tests and monitoring before switching over
β Canary
β Take subset of app servers out of pool
β Deploy to subset
β Smoke tests and monitoring before deploying rest of cluster
β Deploy whole new (app) server instance
β then rewire load-balancer
33. Develop Commit Build Stage Deploy Measure
Deployment with Jenkins & Fabric
Using Git tags
β Set in Jenkins after successful staging run
β Used by deploy in Fabric
def pull():
with cd(env.site_dir):
run('git fetch')
latest_tag = run('git describe --tags --match "ci-passed-staging-*" origin/master',
pty=False)
run('git reset --hard refs/tags/%s' % latest_tag, pty=False)
36. Develop Commit Build Stage Deploy Measure
Deployment with Jenkins & Fabric
def deploy():
dbbackup() # django-dbbackup β to dropbox
changes = pull() # git fetch, git describe, git log, git reset
apply_puppet() # puppet apply β¦ prod.pp
update_requirements() # pip install -r requirements.txt
clean_pyc() # django-extensions command
syncdb() # and βmigrate (South)
collectstatic()
reload_uwsgi() # reload app server
restart_celeryd() # bounce task server
run('git tag -f ci-deployed && git push βtags') # tag deployed version
send_email(changes) # send notification
37. Develop Commit Build Stage Deploy Measure
Decoupling deployment and release
β Feature flags vs feature branches
β Real time control with flags
β Cleanup/maint needed for flags
β Harder/slower to test different combinations in either case
β Good for testing ideas (on/off, A/B, power users, QA etc)
β Gargoyle
β includes optional admin interface
β selective criteria (%age of users, staff only, ...)
β Alternative: Django Waffle
38. Develop Commit Build Stage Deploy Measure
Measurement
β Eyes wide open
β Track system and user behaviour
β Post-deployment
β Error, performance and behaviour heuristics
β Trend monitoring
β Goal conversion rates
43. Rollback options
β Level of automation
β Depends on risk aversion and complexity of environment
β 12+ years of deployment, average 5 deployments per week,
very very few actual rollbacks
β Engineer around it
β lots of small changes β more likely to "roll-forward"
β staged deployment β minimise harm
β Engineer for it
β avoid backwards incompatible data migrations
β tag deployments, keep previous versions handy
44. Rollback options
"My deployment rollback strategy is
like a car with no reverse gear.
You can still go backwards,
but you have to get out and push.
Knowing that makes you drive carefully."
- Me
45. Where to from here
Have an existing app with some gaps?
Think about what's slowing you down the most
β Suggested priorities
β Automated tests (Django built-in)
β Continuous integration (jenkins, django-jenkins)
β Measure all the things (sentry, statsd + graphite, new relic)
β Scripted database (South)
β Scripted deployment (fabric)
β Configuration management (puppet)
β Virtualised development (Vagrant)
β Test separation (test decorator, customise test runner)
β Feature flags (gargoyle)
46. Looking Forward
β Better version pinning
β Fully automated provisioning
β Better test separation and parallelisation
β Combined coverage results
β Reduce dependence on external services
β Make deployment more atomic
β Staged rollouts to cluster β canary deployment
β Make the "big red deploy button" big and red
47. Resources
β Slides β http://slideshare.net/mindsocket/
β Continuous delivery/deployment
β Continuous Delivery Primer - http://www.informit.com/articles/article.aspx?p=1641923
β Anatomy of the Deployment Pipeline - http://www.informit.com/articles/printerfriendly.aspx?p=1621865
β Code as Craft β Etsy http://codeascraft.etsy.com/
β Safe deploying on the cutting edge β Urban Airship http://lanyrd.com/2011/djangocon-us/shbqz/
β Vagrant β http://vagrantup.com
β Vagrant with Fabric - https://gist.github.com/1099132
β Jenkins Build Pipeline Plugin -
http://www.morethanseven.net/2011/03/20/A-continuous-deployment-example-setup.html
β Git/fabric based rollback options
β http://dan.bravender.us/2012/5/11/git-based_fabric_deploys_are_awesome.html
β http://www.askthepony.com/blog/2011/07/setup-a-complete-django-server-deploy-rollback-%E2%80%93-all-in-one-
powerful-script/
β http://lethain.com/deploying-django-with-fabric/