~patrick-hetu/charms/precise/python-django/ansible

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
# Mostly from django-fab-deploy

import os
import sys
from subprocess import Popen, PIPE

import yaml

from fabric.api import env, run, sudo, task, put
from fabric.context_managers import cd, shell_env
from fabric.contrib import files
from fabric.state import output

# Be quiet by default
env.output_prefix = ''
output['running'] = False
output['status'] = False


# helpers
def _sanitize(s):
    s = s.replace(':', '_')
    s = s.replace('-', '_')
    s = s.replace('/', '_')
    s = s.replace('"', '_')
    s = s.replace("'", '_')
    return s


def _config_get(service_name):
    yaml_conf = Popen(['juju', 'get', service_name], stdout=PIPE)
    conf = yaml.safe_load(yaml_conf.stdout)
    return {k: (v['value'] if 'value' in v else v['default']) for k,v in conf['settings'].iteritems()}


def _find_django_admin_cmd():
    for cmd in ['django-admin.py', 'django-admin']:
        remote_environ = run('echo $PATH')
        for path in remote_environ.split(':'):
            path = path.strip('"')
            path = os.path.join(path, cmd)
            if files.exists(path):
                return path

# Initialisation
env.user = 'ubuntu'

d = yaml.safe_load(Popen(['juju', 'status'], stdout=PIPE).stdout)

services = d.get("services", {})
if services is None:
    sys.exit(0)

env.roledefs = {}
for service in services.items():
    if service is None:
        continue

    units = services.get(service[0], {}).get("units", {})
    if units is None:
        continue

    for unit in units.items():
        if 'public-address' in unit[1].keys():
            env.roledefs.setdefault(service[0], []).append(unit[1]['public-address'])
            env.roledefs.setdefault(unit[0], []).append(unit[1]['public-address'])

if not env.roles:
    print "You must select a charm or a unit with the -R option to perform a task"
    print "Charms: %s" % [role for role in env.roledefs.keys() if not '/' in role]
    print "Units: %s" % [host for host in env.roledefs.keys() if '/' in host]
    print
else:
    env.service_name = env.roles[0].split('/')[0]
    env.sanitized_service_name = _sanitize(env.service_name)
    env.conf = _config_get(env.service_name)
    if not env.conf['django_settings']:
        django_settings_modules = '.'.join([env.sanitized_service_name, 'settings'])
        if env.conf['application_path']:
            django_settings_modules = '.'.join([os.path.basename(env.conf['application_path']),
                                                'settings'])
    else:
        django_settings_modules = env.conf['django_settings']

    env.project_dir = os.path.join(env.conf['install_root'], env.sanitized_service_name)
    env.site_path = os.path.join(env.project_dir, env.conf['application_path'])
    if env.conf['python_path']:
        env.python_path = ':'.join([env.conf['install_root'], env.conf['python_path'].replace(',', ':')])
    else:
        env.python_path = env.conf['install_root']


# Debian
@task()
def apt_install(packages):
    """
    Install one or more packages.
    """
    sudo('apt-get install -y %s' % packages)


@task
def apt_update():
    """
    Update APT package definitions.
    """
    sudo('apt-get update')


@task
def apt_dist_upgrade():
    """
    Upgrade all packages.
    """
    sudo('apt-get dist-upgrade -y')


@task
def apt_install_r():
    """
    Install one or more packages listed in your requirements_apt_files.
    """
    with cd(env.project_dir):
        for req_file in env.conf['requirements_apt_files'].split(','):
            sudo("apt-get install -y $(cat %s | tr '\\n' ' '" % req_file)


# Pip
@task
def pip_install(packages):
    """
    Install one or more packages.
    """
    sudo("pip install %s" % packages)


@task
def pip_install_r():
    """
    Install one or more python packages listed in your requirements_pip_files.
    """
    with cd(env.project_dir):
        for req_file in env.conf['requirements_pip_files'].split(','):
            sudo("pip install -r %s" % req_file)


@task
def pip_freeze():
    """
    List installed python packages
    """
    sudo("pip freeze")


# Users
@task
def adduser(username):
    """
    Adduser without password.
    """
    sudo('adduser %s --disabled-password --gecos ""' % username)


# VCS

@task
def pull():
    """
    pull or update your project code on the remote machine.
    """
    with cd(env.project_dir):
        if env.conf['vcs'] is 'bzr':
            run('bzr pull %s' % env.conf['repos_url'])
        if env.conf['vcs'] is 'git':
            run('git pull %s' % env.conf['repos_url'])
        if env.conf['vcs'] is 'hg':
            run('hg pull -u %s' % env.conf['repos_url'])
        if env.conf['vcs'] is 'svn':
            run('svn up %s' % env.conf['repos_url'])

        delete_pyc()
    reload()


# Gunicorn
@task
def reload():
    """
    Reload gunicorn.
    """
    sudo('service %s reload' % env.sanitized_service_name)


# Django
@task
def manage(command):
    """ Runs management commands."""
    django_admin_cmd = _find_django_admin_cmd()

    with cd(env.site_path):
        with shell_env(PYTHONPATH=':'.join([os.path.join(env.site_path, '../'), env.python_path])):
            sudo('%s %s --settings=%s' %
                (django_admin_cmd, command, django_settings_modules),
                 user=env.conf['wsgi_user'])


@task
def load_fixture(fixture_path):
    """ Upload and load a fixture file"""
    fixture_file = fixture_path.split('/')[-1]
    put(fixture_path, '/tmp/')
    manage('loaddata %s' % os.path.join('/tmp/', fixture_file))
    run('rm %s' % os.path.join('/tmp/', fixture_file))


# Utils
@task
def delete_pyc():
    """ Deletes *.pyc files from project source dir """
    with cd(env.project_dir):
        sudo("find . -name '*.pyc' -delete", user="www-data")
        reload()