fixing the example drive.py, properly importing it, and supporting it on VM upstart
[oweals/karmaworld.git] / fabfile.py
1
2 """ Karmaworld Fabric management script
3     Finals Club (c) 2013"""
4
5 import os
6 import ConfigParser
7
8 from fabric.api import cd, env, lcd, prefix, run, sudo, task, local, settings
9 from fabric.contrib import files
10
11 ######### GLOBAL
12 env.user = 'vagrant'
13 env.group = 'vagrant'
14 env.proj_repo = 'git@github.com:FinalsClub/karmaworld.git'
15 env.repo_root = '~/karmaworld'
16 env.proj_root = '/var/www/karmaworld'
17 env.branch = 'prod'
18 env.code_root = env.proj_root
19 env.env_root = env.proj_root
20 env.supervisor_conf = '{0}/confs/{1}/supervisord.conf'.format(env.code_root, env.branch)
21 env.usde_csv = '{0}/confs/acceditation.csv'.format(env.code_root)
22
23 env.use_ssh_config = True
24
25 ######## Define host(s)
26 def here():
27     """
28     Connection information for the local machine
29     """
30     def _custom_local(command):
31         prefixed_command = '/bin/bash -l -i -c "%s"' % command
32         return local(prefixed_command)
33
34     # This is required for the same reason as above
35     env.proj_root = '/var/www/karmaworld'
36     env.cd = lcd
37     env.reqs = 'reqs/dev.txt'
38     env.confs = 'confs/beta'
39     env.branch = 'beta'
40
41
42
43 ####### Define production host
44 @task
45 def prod():
46     """
47     Connection Information for production machine
48     """
49
50     env.user = 'djkarma'
51     env.hosts = ['karmanotes.org']
52     env.proj_root = '/var/www/karmaworld'
53     env.reqs = 'reqs/prod.txt'
54     env.confs = 'confs/prod/'
55     env.branch = 'beta'
56     env.gunicorn_addr = '127.0.0.1:8000'
57
58 ####### Define beta host
59 @task
60 def beta():
61     """
62     Connection Information for beta machine
63     """
64
65     env.user = 'djkarma'
66     env.hosts = ['beta.karmanotes.org']
67     env.proj_root = '/var/www/karmaworld'
68     env.reqs = 'reqs/prod.txt'
69     env.confs = 'confs/prod/'
70     env.branch = 'beta'
71
72 ######## Run Commands in Virutal Environment
73 def virtenv_path():
74     """
75     Builds the virtualenv path.
76     """
77     # not much here now, but maybe useful later.
78     return env.env_root
79
80 def virtenv_exec(command):
81     """
82     Execute command in Virtualenv
83     """
84
85     path = virtenv_path()
86     with prefix('source {0}/bin/activate'.format(path)):
87         run(command)
88
89 ######## Sync database
90 @task
91 def syncdb():
92     """
93     Sync Database
94     """
95     virtenv_exec('{0}/manage.py syncdb --migrate'.format(env.code_root))
96
97
98 ####### Collect Static Files
99 @task
100 def collect_static():
101         """
102         Collect static files (if AWS config. present, push to S3)
103         """
104
105         virtenv_exec('%s/manage.py collectstatic --noinput' % env.code_root )   
106
107 ####### Run Dev Server
108 @task
109 def dev_server():
110         """
111         Runs the built-in django webserver
112         """
113
114         virtenv_exec('%s/manage.py runserver' % env.code_root)  
115
116 ####### Create Virtual Environment
117
118 @task
119 def link_code():
120     """
121     Link the karmaworld repo into the appropriate production location
122     """
123     if not files.exists(env.code_root):
124         run('ln -s {0} {1}'.format(env.repo_root, env.code_root))
125
126 @task
127 def make_virtualenv():
128     """
129     Create our Virtualenv
130     """
131     run('virtualenv {0}'.format(virtenv_path()))
132
133 @task
134 def start_supervisord():
135     """
136     Starts supervisord
137     """
138     virtenv_exec('supervisord -c {0}'.format(env.supervisor_conf))
139
140
141 @task
142 def stop_supervisord():
143     """
144     Restarts supervisord
145     """
146     virtenv_exec('supervisorctl -c {0} shutdown'.format(env.supervisor_conf))
147
148
149 @task
150 def restart_supervisord():
151     """
152     Restarts supervisord
153     """
154     stop_supervisord()
155     start_supervisord()
156
157
158 def supervisorctl(action, process):
159     """
160     Takes as arguments the name of the process as is
161     defined in supervisord.conf and the action that should
162     be performed on it: start|stop|restart.
163     """
164     virtenv_exec('supervisorctl -c {0} {1} {2}'.format(env.supervisor_conf, action, process))
165
166
167 @task
168 def start_celeryd():
169     """
170     Starts the celeryd process
171     """
172     supervisorctl('start', 'celeryd')
173
174
175 @task
176 def stop_celeryd():
177     """
178     Stops the celeryd process
179     """
180     supervisorctl('stop', 'celeryd')
181
182
183 @task
184 def restart_celery():
185     """
186     Restarts the celeryd process
187     """
188     supervisorctl('restart', 'celeryd')
189
190
191 @task
192 def start_gunicorn():
193     """
194     Starts the gunicorn process
195     """
196     supervisorctl('start', 'gunicorn')
197
198
199 @task
200 def stop_gunicorn():
201     """
202     Stops the gunicorn process
203     """
204     supervisorctl('stop', 'gunicorn')
205
206
207 @task
208 def restart_gunicorn():
209     """
210     Restarts the gunicorn process
211     """
212     supervisorctl('restart', 'gunicorn')
213
214
215 ####### Update Requirements
216 @task
217 def update_reqs():
218     virtenv_exec('pip install -r {0}/reqs/{1}.txt'.format(env.repo_root, env.branch))
219
220 ####### Pull new code
221 @task
222 def update_code():
223     virtenv_exec('cd %s; git pull' % env.proj_root )
224
225 def backup():
226     """
227     Create backup using bup
228     """
229     pass
230
231 @task
232 def file_setup():
233     """
234     Deploy expected files and directories from non-apt system services.
235     """
236     ini_parser = ConfigParser.SafeConfigParser()
237     if not ini_parser.read(env.supervisor_conf):
238       raise Exception("Could not parse INI file {0}".format(env.supervisor_conf))
239     for section, option in (('supervisord','logfile'),
240                             ('supervisord','pidfile'),
241                             ('unix_http_server','file'),
242                             ('program:celeryd','stdout_logfile')):
243       filepath = ini_parser.get(section, option)
244       # generate file's directory structure if needed
245       run('mkdir -p {0}'.format(os.path.split(filepath)[0]))
246       # touch a file and change ownership if needed
247       if 'log' in option and not files.exists(filepath):
248           sudo('touch {0}'.format(filepath))
249           sudo('chown {0}:{1} {2}'.format(env.user, env.group, filepath))
250
251 @task
252 def check_secrets():
253     """
254     Ensure secret files exist for syncdb to run.
255     """
256
257     secrets_path = env.code_root + '/karmaworld/secret'
258     secrets_files = ('filepicker.py', 'static_s3.py', 'db_settings.py', 'drive.py', 'client_secrets.json', 'drive.p12')
259
260     errors = []
261     for sfile in secrets_files:
262         ffile = os.path.sep.join((secrets_path,sfile))
263         if not files.exists(ffile):
264             errors.append('{0} missing. Please add and try again.'.format(ffile))
265     if errors:
266         raise Exception('\n'.join(errors))
267
268 @task
269 def fetch_usde():
270     """
271     Download USDE accreditation school CSV.
272     """
273     virtenv_exec('{0}/manage.py fetch_usde_csv {1}'.format(env.code_root, env.usde_csv))
274
275 @task
276 def import_usde():
277     """
278     Import accreditation school CSV into the database and scrub it.
279     """
280     virtenv_exec('{0}/manage.py import_usde_csv {1}'.format(env.code_root, env.usde_csv))
281     virtenv_exec('{0}/manage.py sanitize_usde_schools'.format(env.code_root))
282
283 @task
284 def first_deploy():
285     """
286     Sets up and deploys the project for the first time.
287     """
288     link_code()
289     make_virtualenv()
290     file_setup()
291     check_secrets()
292     update_reqs()
293     syncdb()
294     collect_static()
295     fetch_usde()
296     import_usde()
297     start_supervisord()
298
299
300 @task
301 def deploy():
302     """
303     Deploys the latest changes
304     """
305     update_code()
306     update_reqs()
307     syncdb()
308     collect_static()
309     restart_supervisord()
310 ########## END COMMANDS