Lengthen validity period for compressed assets
[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 ####### Compress Static Files
89 @task
90 def compress_static():
91         """
92         Compress static files
93         """
94
95         virtenv_exec('{0}/manage.py compress'.format(env.code_root))
96
97
98 ####### Run Dev Server
99 @task
100 def dev_server():
101         """
102         Runs the built-in django webserver
103         """
104
105         virtenv_exec('{0}/manage.py runserver'.format(env.code_root))
106
107 ####### Create Virtual Environment
108
109 @task
110 def link_code():
111     """
112     Link the karmaworld repo into the appropriate production location
113     """
114     if not files.exists(env.code_root):
115         run('ln -s {0} {1}'.format(env.repo_root, env.code_root))
116
117 @task
118 def make_virtualenv():
119     """
120     Create our Virtualenv
121     """
122     run('virtualenv {0}'.format(virtenv_path()))
123
124 @task
125 def start_supervisord():
126     """
127     Starts supervisord
128     """
129     virtenv_exec('supervisord -c {0}'.format(env.supervisor_conf))
130
131
132 @task
133 def stop_supervisord():
134     """
135     Restarts supervisord
136     """
137     virtenv_exec('supervisorctl -c {0} shutdown'.format(env.supervisor_conf))
138
139
140 @task
141 def restart_supervisord():
142     """
143     Restarts supervisord, also making sure to load in new config data.
144     """
145     virtenv_exec('supervisorctl -c {0} update; supervisorctl -c {0} restart all'.format(env.supervisor_conf))
146
147
148 def supervisorctl(action, process):
149     """
150     Takes as arguments the name of the process as is
151     defined in supervisord.conf and the action that should
152     be performed on it: start|stop|restart.
153     """
154     virtenv_exec('supervisorctl -c {0} {1} {2}'.format(env.supervisor_conf, action, process))
155
156
157 @task
158 def start_celery():
159     """
160     Starts the celeryd process
161     """
162     supervisorctl('start', 'celeryd')
163
164
165 @task
166 def stop_celery():
167     """
168     Stops the celeryd process
169     """
170     supervisorctl('stop', 'celeryd')
171
172
173 @task
174 def restart_celery():
175     """
176     Restarts the celeryd process
177     """
178     supervisorctl('restart', 'celeryd')
179
180
181 @task
182 def start_gunicorn():
183     """
184     Starts the gunicorn process
185     """
186     supervisorctl('start', 'gunicorn')
187
188
189 @task
190 def stop_gunicorn():
191     """
192     Stops the gunicorn process
193     """
194     supervisorctl('stop', 'gunicorn')
195
196
197 @task
198 def restart_gunicorn():
199     """
200     Restarts the gunicorn process
201     """
202     supervisorctl('restart', 'gunicorn')
203
204
205 ####### Update Requirements
206 @task
207 def install_reqs():
208     # first install must be done without --upgrade for a few packages that break
209     # due to a pip problem.
210     virtenv_exec('pip install -r {0}/reqs/prod.txt'.format(env.code_root))
211
212 @task
213 def update_reqs():
214     # this should generally work to install reqs too, save for a pip problem
215     # with a few packages.
216     virtenv_exec('pip install --upgrade -r {0}/reqs/prod.txt'.format(env.code_root))
217
218 ####### Pull new code
219 @task
220 def update_code():
221     virtenv_exec('cd {0}; git pull'.format(env.code_root))
222
223 def backup():
224     """
225     Create backup using bup
226     """
227     pass
228
229 @task
230 def file_setup():
231     """
232     Deploy expected files and directories from non-apt system services.
233     """
234     ini_parser = ConfigParser.SafeConfigParser()
235     # read remote data into a file like object
236     data_flo = StringIO(run('cat {supervisor_conf}'.format(**env)))
237     ini_parser.readfp(data_flo)
238     for section, option in (('supervisord','logfile'),
239                             ('supervisord','pidfile'),
240                             ('unix_http_server','file'),
241                             ('program:celeryd','stdout_logfile')):
242       if not ini_parser.has_section(section):
243           raise Exception("Could not parse INI file {supervisor_conf}".format(**env))
244       filepath = ini_parser.get(section, option)
245       # generate file's directory structure if needed
246       run('mkdir -p {0}'.format(os.path.split(filepath)[0]))
247       # touch a file and change ownership if needed
248       if 'log' in option and not files.exists(filepath):
249           sudo('touch {0}'.format(filepath))
250           sudo('chown {0}:{1} {2}'.format(env.django_user, env.group, filepath))
251
252 @task
253 def check_secrets():
254     """
255     Ensure secret files exist for syncdb to run.
256     """
257
258     secrets_path = env.code_root + '/karmaworld/secret'
259     secrets_files = ('filepicker.py', 'static_s3.py', 'db_settings.py', 'drive.py', 'client_secrets.json', 'drive.p12')
260
261     errors = []
262     for sfile in secrets_files:
263         ffile = os.path.sep.join((secrets_path,sfile))
264         if not files.exists(ffile):
265             errors.append('{0} missing. Please add and try again.'.format(ffile))
266     if errors:
267         raise Exception('\n'.join(errors))
268
269 @task
270 def fetch_usde():
271     """
272     Download USDE accreditation school CSV.
273     """
274     virtenv_exec('{0}/manage.py fetch_usde_csv {1}'.format(env.code_root, env.usde_csv))
275
276 @task
277 def import_usde():
278     """
279     Import accreditation school CSV into the database and scrub it.
280     """
281     virtenv_exec('{0}/manage.py import_usde_csv {1}'.format(env.code_root, env.usde_csv))
282     virtenv_exec('{0}/manage.py sanitize_usde_schools'.format(env.code_root))
283
284 @task
285 def first_deploy():
286     """
287     Sets up and deploys the project for the first time.
288     """
289     link_code()
290     make_virtualenv()
291     file_setup()
292     check_secrets()
293     install_reqs()
294     syncdb()
295     collect_static()
296     fetch_usde()
297     import_usde()
298     start_supervisord()
299     print "You should run `manage.py createsuperuser` in the virtual environment"
300
301
302 @task
303 def deploy():
304     """
305     Deploys the latest changes
306     """
307     update_code()
308     update_reqs()
309     syncdb()
310     compress_static()
311     collect_static()
312     restart_supervisord()
313 ########## END COMMANDS