dummy commit
[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 @task
205 def flush_memcache():
206     """
207     Clear everything cached in memcached
208     """
209     virtenv_exec('echo "flush_all" | nc localhost 11211')
210
211 ####### Update Requirements
212 @task
213 def install_reqs():
214     # first install must be done without --upgrade for a few packages that break
215     # due to a pip problem.
216     virtenv_exec('pip install -r {0}/reqs/prod.txt'.format(env.code_root))
217
218 @task
219 def update_reqs():
220     # this should generally work to install reqs too, save for a pip problem
221     # with a few packages.
222     virtenv_exec('pip install --upgrade -r {0}/reqs/prod.txt'.format(env.code_root))
223
224 ####### Pull new code
225 @task
226 def update_code():
227     virtenv_exec('cd {0}; git pull'.format(env.code_root))
228
229 def backup():
230     """
231     Create backup using bup
232     """
233     pass
234
235 @task
236 def file_setup():
237     """
238     Deploy expected files and directories from non-apt system services.
239     """
240     ini_parser = ConfigParser.SafeConfigParser()
241     # read remote data into a file like object
242     data_flo = StringIO(run('cat {supervisor_conf}'.format(**env)))
243     ini_parser.readfp(data_flo)
244     for section, option in (('supervisord','logfile'),
245                             ('supervisord','pidfile'),
246                             ('unix_http_server','file'),
247                             ('program:celeryd','stdout_logfile')):
248       if not ini_parser.has_section(section):
249           raise Exception("Could not parse INI file {supervisor_conf}".format(**env))
250       filepath = ini_parser.get(section, option)
251       # generate file's directory structure if needed
252       run('mkdir -p {0}'.format(os.path.split(filepath)[0]))
253       # touch a file and change ownership if needed
254       if 'log' in option and not files.exists(filepath):
255           sudo('touch {0}'.format(filepath))
256           sudo('chown {0}:{1} {2}'.format(env.django_user, env.group, filepath))
257
258 @task
259 def check_secrets():
260     """
261     Ensure secret files exist for syncdb to run.
262     """
263
264     secrets_path = env.code_root + '/karmaworld/secret'
265     secrets_files = ('filepicker.py', 'static_s3.py', 'drive.py', 'client_secrets.json', 'drive.p12')
266
267     errors = []
268     for sfile in secrets_files:
269         ffile = os.path.sep.join((secrets_path,sfile))
270         if not files.exists(ffile):
271             errors.append('{0} missing. Please add and try again.'.format(ffile))
272     if errors:
273         raise Exception('\n'.join(errors))
274
275 @task
276 def fetch_usde():
277     """
278     Download USDE accreditation school CSV.
279     """
280     virtenv_exec('{0}/manage.py fetch_usde_csv {1}'.format(env.code_root, env.usde_csv))
281
282 @task
283 def import_usde():
284     """
285     Import accreditation school CSV into the database and scrub it.
286     """
287     virtenv_exec('{0}/manage.py import_usde_csv {1}'.format(env.code_root, env.usde_csv))
288     virtenv_exec('{0}/manage.py sanitize_usde_schools'.format(env.code_root))
289
290 @task
291 def first_deploy():
292     """
293     Sets up and deploys the project for the first time.
294     """
295     link_code()
296     make_virtualenv()
297     file_setup()
298     check_secrets()
299     install_reqs()
300     syncdb()
301     compress_static()
302     collect_static()
303     fetch_usde()
304     import_usde()
305     start_supervisord()
306     print "You should run `manage.py createsuperuser` in the virtual environment"
307
308
309 @task
310 def deploy():
311     """
312     Deploys the latest changes
313     """
314     update_code()
315     update_reqs()
316     syncdb()
317     compress_static()
318     collect_static()
319     restart_supervisord()
320 ########## END COMMANDS