~allanlesage/qlbr/fab-deployment

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
import os
import logging
from tempfile import mkdtemp, mktemp

from django.core import management
from fabric.api import run, sudo, local, put, env, settings, abort, cd
from fabric.contrib.console import confirm
from fabric.contrib.files import append, contains
from fabric.utils import abort

from deployment import (staging_settings,
                        production_settings,
                        testing_settings)


VALID_DEPLOYMENT_TYPES = ['production',
                          'staging',
                          'testing']


def apt_get_everything():
    """apt-get everything required to be a qlbr."""

    sudo("apt-get install -y bzr apache2 libapache2-mod-wsgi \
          python-django postgresql python-psycopg2 python-mock")

def restart_postgres():
    """Restart our fav DB server."""

    sudo("service postgresql restart")

def ubuntu_postgres_user_exists():
    """Does the postgres user exist and can I have her phone number?"""

    return sudo("psql postgres -tAc \"SELECT 1 FROM pg_roles WHERE rolname='ubuntu'\"",
                  user='postgres') != 1

def create_ubuntu_postgres_user():
    """Create 'ubuntu' postgres user."""

    with settings(warn_only=True):
        sudo("createuser -U postgres -s ubuntu -P", user='postgres')
        sudo("createdb ubuntu", user='postgres')

def database_exists(name='qlbr'):
    """Does the database exist?"""

    result = sudo("psql -tAc \"SELECT * FROM pg_database WHERE datname='{}';\"".format(name),
                  user='postgres')
    return result != ""

def destroy_database(name='qlbr'):
    """Destroy postgresql qlbr database."""

    with settings(warn_only=True):
        # we could warn on this if it doesn't exist (but we don't expect to)
        sudo("dropdb {}".format(name),
             user='postgres')

def create_database(name='qlbr'):
    """Create a fresh db for user ubuntu."""

    sudo("createdb -E utf8 -O ubuntu {} -T template0".format(name),
         user='postgres')

def adjust_pg_hba_conf():
    """We need md5 password checking for localhost."""
 
    # TODO: this sed dinna work under fabric WTF:
    # sudo sed 's/^\(local\s*all\s*all\s*\)\(.*\)$/\1md5/' /etc/postgresql/9.3/main/pg_hba.conf
    # . . . so we're just copying a baked file
    put("./deployment/pg_hba.conf", "/etc/postgresql/9.3/main/", use_sudo=True)
    restart_postgres()

def setup_database(name='qlbr'):
    """Create postgresql qlbr user and database.

    Name defaults to 'qlbr' for production, suggest
    'qlbr-staging' for staging.

    """
    adjust_pg_hba_conf()
    if not ubuntu_postgres_user_exists():
        create_ubuntu_postgres_user()
    if database_exists(name):
        destroy_database(name)
    create_database(name)
    restart_postgres()

def checkout_qlbr(install_dir, branch="lp:helipad"):
    """Checkout branch into 'qlbr' in the user's home dir.

    Bazaar and fabric don't get along so we can't just bzr branch,
    instead cp from a local checkout.

    """
    # blow away whatever's there at the install path
    sudo("rm -rf {}/*".format(install_dir))
    run("mkdir -p {}".format(install_dir))

    # get a local checkout of the source, pack, and ship
    tmp_dir = mkdtemp()
    tmp_install_dir = os.path.join(tmp_dir, 'qlbr')
    local("bzr branch {} {}".format(branch, tmp_install_dir))
    # this is kind-of silly but the tar -C option wasn't working with globbing
    orig_dir = os.getcwd()
    os.chdir(tmp_install_dir)
    local("tar --exclude fabfile.pyc --overwrite -czvf /tmp/qlbr-source.tar.gz *")
    os.chdir(orig_dir)
    put("/tmp/qlbr-source.tar.gz",
        install_dir,
        use_sudo=True)
    with cd(install_dir):
        run("tar -xvf qlbr-source.tar.gz")
    run("rm {}".format(os.path.join(install_dir, "qlbr-source.tar.gz")))
    local("rm -rf {}".format(tmp_install_dir))

    # set perms so that www-data can access
    sudo("chown -R ubuntu:qlbr {}".format(install_dir))
    sudo("chmod -R g+rw {}".format(install_dir))

def restart_apache():
    """Restart our fav webserver."""

    sudo("service apache2 restart")

def configure_apache(apache_config_filepath):
    """Configure apache2: copy our site config, set up perms, etc.

    'deployment/qlbr-staging', e.g.

    """
    sudo("cp {} /etc/apache2/sites-available/".format(apache_config_filepath))
    sudo("adduser www-data qlbr")
    # we'll take the last term of the apache config path as the site name to enable
    site_name = os.path.split(apache_config_filepath)[-1]
    sudo("a2ensite {}".format(site_name))
    restart_apache()

def setup_users():
    """Create a qlbr group and add ubuntu to it.

    This facilitates apache access.

    """
    with settings(warn_only=True):
        sudo("addgroup qlbr")
        sudo("adduser ubuntu qlbr")

def copy_local_settings(install_dir,
                        settings_filename="production_settings.py"):
    """Copy settings into place."""

    sudo("cp {} {}".format(
            os.path.join(install_dir,
                         'deployment',
                         settings_filename),
            os.path.join(install_dir,
                         "qlbr",
                         "local_settings.py")),
         user='ubuntu')

def collect_static_media(install_dir):
    """Use the Django utility to collect all of our static files."""

    with cd(install_dir):
        sudo("python manage.py collectstatic --noinput", user='ubuntu')

def setup_cron_job(install_dir):
    """Add our qa-dashboard-update.sh to crontab."""

    cron_job_line = "42 * * * * {}/scripts/qa-dashboard-update.sh".format(install_dir)
    tmp_cron_filename = mktemp()
    # our crontab might be empty; ignore that error
    with settings(warn_only=True):
        run("crontab -l 2>/dev/null > {}".format(tmp_cron_filename),)
    if contains(tmp_cron_filename, cron_job_line):
        print cron_job_line + " already in crontab."
    else:
        append(tmp_cron_filename, cron_job_line)
        run("crontab {}".format(tmp_cron_filename))
        run("rm {}".format(tmp_cron_filename))

def deploy(deployment_type, branch="lp:qlbr"):
    """Push this branch to the production site.

    deployment_type should be one of 'production', 'staging', or 'testing'.
    """

    if deployment_type not in VALID_DEPLOYMENT_TYPES:
        abort("Deployment must be one of {}.".format(VALID_DEPLOYMENT_TYPES))
    install_dir = {'production': production_settings.INSTALL_PATH,
                   'staging': staging_settings.INSTALL_PATH,
                   'testing': testing_settings.INSTALL_PATH}[deployment_type]
    checkout_qlbr(install_dir, branch)
    apache_config_filename = {'production': 'qlbr',
                              'staging': 'qlbr-staging',
                              'testing': 'qlbr-testing'}[deployment_type]
    configure_apache(
        os.path.join(install_dir,
                     'deployment',
                     apache_config_filename))
    setup_cron_job(install_dir)
    # compose a settings_filename, e.g. testing_settings.py
    settings_filename = "settings_{}.py".format(deployment_type)
    copy_local_settings(install_dir,
                        settings_filename)
    collect_static_media(install_dir)
    with cd(install_dir):
        run("python manage.py syncdb")
        run("python manage.py migrate")

def setup(deployment_type, branch="lp:qlbr"):
    """Setup the qlbr site on a new server.

    deployment_type should be one of 'production', 'staging', or 'testing'.

    NOTE: DROPS DB.

    """
    if deployment_type not in VALID_DEPLOYMENT_TYPES:
        abort("deployment_type must be one of {}.".format(VALID_DEPLOYMENT_TYPES))
    apt_get_everything()
    setup_users()
    database_name = {'production': 'qlbr',
                     'staging': 'qlbr-staging',
                     'testing': 'qlbr-testing'}[deployment_type]
    setup_database(database_name)
    deploy(deployment_type, branch=branch)