Keyword cleanup
[oweals/karmaworld.git] / fabfile.py
1 """ Karmaworld Fabric management script
2     Finals Club (c) 2013"""
3
4 import os
5 import ConfigParser
6 from cStringIO import StringIO
7
8 from fabric.api import cd, lcd, prefix, run, sudo, task, local, settings
9 from fabric.state import env as fabenv
10 from fabric.contrib import files
11
12 from dicthelpers import fallbackdict
13
14 # Use local SSH config for connections if available.
15 fabenv['use_ssh_config'] = True
16
17 ######## env wrapper
18 # global environment variables fallback to fabric env variables
19 # (also getting vars will do format mapping on strings with env vars)
20 env = fallbackdict(fabenv)
21
22 ######### GLOBALS
23 env.django_user = '{user}' # this will be different when sudo/django users are
24 env.group = 'www-data'
25 env.proj_repo = 'git@github.com:FinalsClub/karmaworld.git'
26 env.repo_root = '/home/{django_user}/karmaworld'
27 env.proj_root = '/var/www/karmaworld'
28 env.branch = 'prod' # only used for supervisor conf two lines below. cleanup?
29 env.code_root = env.proj_root
30 env.supervisor_conf = '{code_root}/confs/{branch}/supervisord.conf'
31 env.usde_csv = '{code_root}/confs/accreditation.csv'
32
33 ######## Run Commands in Virtual Environment
34 def virtenv_path():
35     """
36     Find and memoize the virtualenv for use internally.
37     """
38     default_venv = env.proj_root + '/venv/bin/activate'
39
40     # Return environment root if its been memoized
41     if 'env_root' in env and env['env_root']:
42         return env['env_root']
43
44     # Not memoized. Try to find a single unique virtual environment.
45     with settings(warn_only=True):
46         outp = run("find -L {0} -path '*/bin/activate' | grep -v '/local/'".format(env.proj_root))
47     if not len(outp) or len(outp.splitlines()) != 1:
48         # Cannot find any virtualenv or found multiple virtualenvs. 
49         if len(outp) and default_venv not in outp:
50             # Multiple venvs and the default is not present.
51             raise Exception('Cannot determine the appropriate virtualenv.')
52         # If there are no virtualenvs, then use the default (this will create
53         # one if being called by make_virtualenv, otherwise it will cause an
54         # error).
55         # If there are multiple virtualenvs and the default is in their midst,
56         # use the default.
57         outp = default_venv
58     # Pop off the /bin/activate from /venv/bin/activate
59     outp = os.path.sep.join(outp.split(os.path.sep)[:-2])
60     env['env_root'] = outp
61     return outp
62
63 def virtenv_exec(command):
64     """
65     Execute command in Virtualenv
66     """
67     with prefix('source {0}/bin/activate'.format(virtenv_path())):
68         run(command)
69
70 ######## Sync database
71 @task
72 def syncdb():
73     """
74     Sync Database
75     """
76     virtenv_exec('{0}/manage.py syncdb --migrate --noinput'.format(env.code_root))
77
78
79 ####### Collect Static Files
80 @task
81 def collect_static():
82         """
83         Collect static files (if AWS config. present, push to S3)
84         """
85
86         virtenv_exec('{0}/manage.py collectstatic --noinput'.format(env.code_root))
87
88 ####### Run Dev Server
89 @task
90 def dev_server():
91         """
92         Runs the built-in django webserver
93         """
94
95         virtenv_exec('{0}/manage.py runserver'.format(env.code_root))
96
97 ####### Create Virtual Environment
98
99 @task
100 def link_code():
101     """
102     Link the karmaworld repo into the appropriate production location
103     """
104     if not files.exists(env.code_root):
105         run('ln -s {0} {1}'.format(env.repo_root, env.code_root))
106
107 @task
108 def make_virtualenv():
109     """
110     Create our Virtualenv
111     """
112     run('virtualenv {0}'.format(virtenv_path()))
113
114 @task
115 def start_supervisord():
116     """
117     Starts supervisord
118     """
119     virtenv_exec('supervisord -c {0}'.format(env.supervisor_conf))
120
121
122 @task
123 def stop_supervisord():
124     """
125     Restarts supervisord
126     """
127     virtenv_exec('supervisorctl -c {0} shutdown'.format(env.supervisor_conf))
128
129
130 @task
131 def restart_supervisord():
132     """
133     Restarts supervisord, also making sure to load in new config data.
134     """
135     virtenv_exec('supervisorctl -c {0} update; supervisorctl -c {0} restart all'.format(env.supervisor_conf))
136
137
138 def supervisorctl(action, process):
139     """
140     Takes as arguments the name of the process as is
141     defined in supervisord.conf and the action that should
142     be performed on it: start|stop|restart.
143     """
144     virtenv_exec('supervisorctl -c {0} {1} {2}'.format(env.supervisor_conf, action, process))
145
146
147 @task
148 def start_celery():
149     """
150     Starts the celeryd process
151     """
152     supervisorctl('start', 'celeryd')
153
154
155 @task
156 def stop_celery():
157     """
158     Stops the celeryd process
159     """
160     supervisorctl('stop', 'celeryd')
161
162
163 @task
164 def restart_celery():
165     """
166     Restarts the celeryd process
167     """
168     supervisorctl('restart', 'celeryd')
169
170
171 @task
172 def start_gunicorn():
173     """
174     Starts the gunicorn process
175     """
176     supervisorctl('start', 'gunicorn')
177
178
179 @task
180 def stop_gunicorn():
181     """
182     Stops the gunicorn process
183     """
184     supervisorctl('stop', 'gunicorn')
185
186
187 @task
188 def restart_gunicorn():
189     """
190     Restarts the gunicorn process
191     """
192     supervisorctl('restart', 'gunicorn')
193
194
195 ####### Update Requirements
196 @task
197 def install_reqs():
198     # first install must be done without --upgrade for a few packages that break
199     # due to a pip problem.
200     virtenv_exec('pip install -r {0}/reqs/prod.txt'.format(env.code_root))
201
202 @task
203 def update_reqs():
204     # this should generally work to install reqs too, save for a pip problem
205     # with a few packages.
206     virtenv_exec('pip install --upgrade -r {0}/reqs/prod.txt'.format(env.code_root))
207
208 ####### Pull new code
209 @task
210 def update_code():
211     virtenv_exec('cd {0}; git pull'.format(env.code_root))
212
213 def backup():
214     """
215     Create backup using bup
216     """
217     pass
218
219 @task
220 def file_setup():
221     """
222     Deploy expected files and directories from non-apt system services.
223     """
224     ini_parser = ConfigParser.SafeConfigParser()
225     # read remote data into a file like object
226     data_flo = StringIO(run('cat {supervisor_conf}'.format(**env)))
227     ini_parser.readfp(data_flo)
228     for section, option in (('supervisord','logfile'),
229                             ('supervisord','pidfile'),
230                             ('unix_http_server','file'),
231                             ('program:celeryd','stdout_logfile')):
232       if not ini_parser.has_section(section):
233           raise Exception("Could not parse INI file {supervisor_conf}".format(**env))
234       filepath = ini_parser.get(section, option)
235       # generate file's directory structure if needed
236       run('mkdir -p {0}'.format(os.path.split(filepath)[0]))
237       # touch a file and change ownership if needed
238       if 'log' in option and not files.exists(filepath):
239           sudo('touch {0}'.format(filepath))
240           sudo('chown {0}:{1} {2}'.format(env.django_user, env.group, filepath))
241
242 @task
243 def check_secrets():
244     """
245     Ensure secret files exist for syncdb to run.
246     """
247
248     secrets_path = env.code_root + '/karmaworld/secret'
249     secrets_files = ('filepicker.py', 'static_s3.py', 'db_settings.py', 'drive.py', 'client_secrets.json', 'drive.p12')
250
251     errors = []
252     for sfile in secrets_files:
253         ffile = os.path.sep.join((secrets_path,sfile))
254         if not files.exists(ffile):
255             errors.append('{0} missing. Please add and try again.'.format(ffile))
256     if errors:
257         raise Exception('\n'.join(errors))
258
259 @task
260 def fetch_usde():
261     """
262     Download USDE accreditation school CSV.
263     """
264     virtenv_exec('{0}/manage.py fetch_usde_csv {1}'.format(env.code_root, env.usde_csv))
265
266 @task
267 def import_usde():
268     """
269     Import accreditation school CSV into the database and scrub it.
270     """
271     virtenv_exec('{0}/manage.py import_usde_csv {1}'.format(env.code_root, env.usde_csv))
272     virtenv_exec('{0}/manage.py sanitize_usde_schools'.format(env.code_root))
273
274 @task
275 def first_deploy():
276     """
277     Sets up and deploys the project for the first time.
278     """
279     link_code()
280     make_virtualenv()
281     file_setup()
282     check_secrets()
283     install_reqs()
284     syncdb()
285     collect_static()
286     fetch_usde()
287     import_usde()
288     start_supervisord()
289     print "You should run `manage.py createsuperuser` in the virtual environment"
290
291
292 @task
293 def deploy():
294     """
295     Deploys the latest changes
296     """
297     update_code()
298     update_reqs()
299     syncdb()
300     collect_static()
301     restart_supervisord()
302 ########## END COMMANDS