Skip to content

Instantly share code, notes, and snippets.

@greut
Created July 22, 2014 09:40
Show Gist options
  • Select an option

  • Save greut/4a322e93033581c0f4a1 to your computer and use it in GitHub Desktop.

Select an option

Save greut/4a322e93033581c0f4a1 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
## This file is part of Invenio.
## Copyright (C) 2014 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""
Basic fabric file for deploying invenio applications.
source: https://flask-cn.readthedocs.org/en/latest/patterns/fabric/
"""
from __future__ import unicode_literals
import json
from fabric.api import *
from fabric.utils import error
from fabric.contrib.files import exists
# the user to use for the remote commands
env.user = "invenio"
# the directory where to install things
env.directory = "/home/invenio/www"
# symlink name
env.symlink = "current"
# the servers where the commands are executed
#env.hosts = ["server1.example.com", "server2.example.com"]
env.hosts = ['127.0.0.1:2222']
@task
def setup():
"""Installing the python requirements.
If you want to have MySQL and redis on this machine as well, you'll have to
do it by yourself.
"""
sudo("apt-get update -q")
sudo("sudo apt-get install -y build-essential git python-dev python-pip "
"libmysqlclient-dev libxml2-dev libxslt-dev libjpeg-dev "
"libfreetype6-dev libtiff-dev")
sudo("pip install -U virtualenv pip")
@task
def vagrant():
# change from the default user to 'vagrant'
env.user = 'vagrant'
# connect to the port-forwarded ssh
env.directory = "/home/{env.user}/www".format(env=env)
# use vagrant ssh key
result = local('vagrant ssh-config f86a699 | grep IdentityFile', capture=True)
env.key_filename = result.split()[1]
@task
def pack():
"""Create a new source distribution as tarball."""
with open(".bowerrc") as fp:
bower = json.load(fp)
local("inveniomanage assets build --directory {directory}/gen"
.format(**bower))
return local("python setup.py sdist --formats=gztar", capture=False) \
.succeeded
@task
def package():
"""Return the name of the package to be installed."""
return local("python setup.py --fullname", capture=True).strip()
@task
def create_virtualenv():
"""Create the virtualenv."""
package = execute("package")[env.hosts[0]]
venv = "{0}/{1}".format(env.directory, package)
with cd(env.directory):
# 1. create virtualenv
if exists(package):
return error("This version {0} is already installed."
.format(package))
return run("virtualenv {0}".format(package)).succeeded
@task
def destroy_virtualenv():
"""Destroy the virtualenv."""
package = execute("package")[env.hosts[0]]
with cd(env.directory):
run("rm -rf {0}".package)
@task
def install():
"""Install package.
It does set up the PIP DOWNLOAD CACHE so next installation will be faster.
NB: it does install through requirements.txt which installs in editable
mode. It should eventually say `python setup.py install`.
"""
package = execute("package")[env.hosts[0]]
venv = "{0}/{1}".format(env.directory, package)
if not exists(venv):
return error("Meh? I need a virtualenv first.")
put("dist/{0}.tar.gz".format(package), "/tmp/app.tgz")
run("mkdir -p {0}/src".format(venv))
with cd("{0}/src".format(venv)):
run("tar xzf /tmp/app.tgz")
run("rm -rf /tmp/app.tgz")
with cd("{0}/src/{1}".format(venv, package)):
with shell_env(PIP_DOWNLOAD_CACHE="{0}/.pip_download_cache"
.format(env.directory)):
# install
success = run("{0}/bin/pip install -r requirements.txt" \
.format(venv)).succeeded
if success:
# post install
run("{0}/bin/inveniomanage collect".format(venv))
cfg = "var/invenio.base-instance/invenio.cfg"
old = "{0}/{1}".format(env.directory, env.symlink)
if exists("{old}/{cfg}".format(old=old, cfg=cfg)):
run("cp {old}/{cfg} {new}/{cfg}".format(old=old, new=venv,
cfg=cfg))
else:
error("No existing configuration found, please do!")
return success
@task
def restart_servers():
"""Restart the servers (web, celery)."""
run("touch {0}/wsgi.py".format(env.directory)) # µWSGI/mod_wsgi
puts
return True
@task
def deploy():
"""Deploy the package on the hosts."""
package = execute("package")[env.hosts[0]]
if not execute("create_virtualenv"):
return False
if not execute("install"):
# destroying the virtualenv to be sure nobody ever tries to symlink it.
execute("destroy_virtualenv")
error("Installation failed")
# update the symlink
with cd(env.directory):
run("rm {1}; ln -s {0} {1}".format(package, env.symlink))
return execute("restart_servers")
@task
def rollback():
"""Rollback one version older."""
# 1. figure out what is the version right before the `current` one
# 2. update the symlink to it
# 3. delete previous current version
# 4. profit
return False
@task
def cleanup():
"""Clean up old versions"""
with cd(env.directory):
run("ls -l")
# 1. list all the versions present in the env.directory (name + date)
# 2. let the user pick the last one to keep
# 3. remove all the ones older than the one picked
# 4. profit!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment