/
bootstrap.py
executable file
·307 lines (246 loc) · 9.97 KB
/
bootstrap.py
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#!/usr/bin/env python
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
"""
This bootstrap script does the first stage of prep work for a Django
site that consists of multiple apps pulled in from separate repos via
git submodules. The script does just enough so that our subsequent
Django management commands will work -- they need Django to be installed
and minimally configured, and they need the apps to be present
and linked into the right place relative to the PYTHONPATH.
This script is intended to be generic across sites. Please don't put
any site-specific customizations in here. If you need to modify it,
please check your changes into
geocamDjangoSiteSkeleton/skel/bin/bootstrap.py so other sites can
benefit. Normally we would put code like this in geocamUtil, but the
whole reason we need a bootstrap step is to make sure things like
geocamUtil are available...
"""
import os
import sys
from glob import glob
import logging
from random import choice
import re
DEFAULT_SITE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SOURCEME_NAME = 'sourceme.sh'
SETTINGS_NAME = 'settings.py'
STATUS_PATH_TEMPLATE = 'build/management/bootstrap/%sStatus.txt'
ACTIONS = (dict(name='gitInitSubmodules',
desc="Init and update submodules",
confirm=True),
dict(name='gitSubmodulesMasterBranch',
desc='Set submodules to be on their master branch for development',
confirm=True),
#dict(name='linkSubmodules',
# desc='Link submodules into apps directory',
# confirm=True),
dict(name='installSubModuleRequirements',
desc='Install Python modules listed in the requirements for each submodule',
confirm=True),
dict(name='installSiteRequirements',
desc='Install Python modules listed in the site-level requirements',
confirm=True),
dict(name='genSourceme',
needed='needSourceme',
desc='Create initial sourceme.sh file'),
dict(name='genSettings',
needed='needSettings',
desc='Create initial settings.py file'),
)
ACTION_DICT = dict([(a['name'], a) for a in ACTIONS])
def getConfirmation(opts, actionStr):
if opts.yes:
sys.stdout.write(actionStr + '? [Y/n] ')
print 'y'
return True
else:
while 1:
sys.stdout.write(actionStr + '? [Y/n] ')
response = raw_input().strip().lower()
if not response:
return True
elif response == 'y':
return True
elif response == 'n':
return False
def dosys(cmd, continueOnError=False):
if cmd.startswith('sudo'):
# force print before user gets password prompt
print 'running: ' + cmd
else:
logging.info('Running: ' + cmd)
ret = os.system(cmd)
if ret != 0:
if continueOnError:
logging.warning('WARNING: Command returned non-zero return value %d', ret)
else:
logging.error('ERROR: Command returned non-zero return value %d', ret)
sys.exit(1)
def writeFileMakeDir(path, text):
d = os.path.dirname(path)
if not os.path.exists(d):
os.makedirs(d)
f = file(path, 'w')
f.write(text + '\n')
f.close()
def fillTemplate(inputFile, outputFile, context):
if os.path.exists(outputFile):
logging.warning('WARNING: File %s exists, not overwriting. Move current version out of the way to regenerate', outputFile)
return
logging.info('generating %s', outputFile)
from django.template import Template, Context
from django.conf import settings
if not settings.configured:
settings.configure()
tmpl = Template(file(inputFile, 'r').read())
text = tmpl.render(Context(context))
file(outputFile, 'w').write(text)
######################################################################
# ACTION DEFINITIONS
def gitInitSubmodules(opts):
dosys('git submodule init')
dosys('git submodule update')
def gitSubmodulesMasterBranch(opts):
# avoid "(no branch)"
dosys('git submodule foreach git checkout master')
def linkSubmodules(opts):
if not os.path.exists('apps'):
os.mkdir('apps')
# assumes each submodule app has a models dir or a models.py file
submoduleAppDirs = [os.path.dirname(d) for d in glob('submodules/*/*/models*')]
for src in submoduleAppDirs:
appName = os.path.basename(src)
relativeSrc = '../%s' % src
dst = 'apps/%s' % appName
if os.path.lexists(dst):
logging.debug(' %s -> %s skipped (already exists)', dst, relativeSrc)
else:
logging.debug(' %s -> %s', dst, relativeSrc)
os.symlink(relativeSrc, dst)
def hasRequirements(reqsFile):
for line in file(reqsFile, 'r'):
if not re.match(r'^\s*(\#.*)?$', line):
return True
return False
def installRequirements(reqsFile):
needSudo = 'VIRTUAL_ENV' not in os.environ
if needSudo:
sudoStr = 'sudo '
else:
sudoStr = ''
if hasRequirements(reqsFile):
dosys('%spip install -r %s' % (sudoStr, reqsFile))
else:
logging.info('requirements file %s is empty', reqsFile)
def installSubModuleRequirements(opts):
for reqs in glob('submodules/*/requirements.txt'):
installRequirements(reqs)
def installSiteRequirements(opts):
installRequirements('management/siteRequirements.txt')
def needSourceme(opts):
return not os.path.exists(SOURCEME_NAME)
def genSourceme(opts):
fillTemplate('management/templates/%s' % SOURCEME_NAME,
SOURCEME_NAME,
dict(virtualEnvDir=os.environ.get('VIRTUAL_ENV', None),
parentDir=os.path.dirname(os.path.abspath(os.getcwd())),
appsDir=os.path.abspath('apps')
))
def needSettings(opts):
return not os.path.exists(SETTINGS_NAME)
def genSettings(opts):
secretKey = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for _i in range(50)])
fillTemplate('management/templates/%s' % SETTINGS_NAME,
SETTINGS_NAME,
dict(secretKey=secretKey))
def needAction(opts, action):
statusFile = STATUS_PATH_TEMPLATE % action['name']
if os.path.exists(statusFile):
return file(statusFile, 'r').read().strip()
else:
return False
######################################################################
# TOP-LEVEL CODE
def doAction(opts, action):
status = 'NEEDED'
# check if we need to do the action
neededName = action.get('needed', None)
if neededName:
# special check function defined for this action
neededFunc = globals()[neededName]
actionIsNeeded = neededFunc(opts)
if not actionIsNeeded:
status = 'NOT_NEEDED'
else:
# standard check function
checkStatus = needAction(opts, action)
if checkStatus:
status = checkStatus
if status != 'NEEDED':
if opts.retry:
logging.info('Would skip %s, status is %s, but running in retry mode', action['name'], status)
else:
logging.info('Skipping step %s, status is %s', action['name'], status)
return
# confirm with user
if (opts.retry or 'confirm' in action) and not getConfirmation(opts, action['desc']):
writeFileMakeDir(STATUS_PATH_TEMPLATE % action['name'], 'UNWANTED')
return
# do the action
actionFunc = globals()[action['name']]
actionFunc(opts)
# mark completion (unless special check function is defined)
if not neededName:
writeFileMakeDir(STATUS_PATH_TEMPLATE % action['name'], 'DONE')
def doit(opts, args):
os.chdir(opts.siteDir)
if not opts.retry and os.path.exists('build/management/bootstrap/bootstrapStatus.txt'):
sys.exit(0)
print 'Bootstrapping...'
logging.basicConfig(level=(logging.WARNING - opts.verbose * 10),
format='%(message)s')
if args:
for arg in args:
if arg not in ACTION_DICT:
print >> sys.stderr, 'ERROR: there is no action %s' % arg
print >> sys.stderr, 'Available actions are: %s' % (' '.join([a['name'] for a in ACTIONS]))
sys.exit(1)
actions = [ACTION_DICT[arg] for arg in args]
else:
actions = ACTIONS
logging.info('Working in %s', os.getcwd())
for action in actions:
doAction(opts, action)
# mark overall completion
writeFileMakeDir(STATUS_PATH_TEMPLATE % 'bootstrap', 'DONE')
print '\nFinished bootstrapping\n'
sys.path.insert(0, os.path.dirname(opts.siteDir))
from geocamMapFasten.djangoWsgi import getEnvironmentFromSourceMe
getEnvironmentFromSourceMe()
def main():
import optparse
parser = optparse.OptionParser('usage: %prog [action1 action2 ...]')
parser.add_option('-y', '--yes',
action='store_true', default=False,
help='Automatically answer yes to all confirmation questions')
parser.add_option('-s', '--siteDir',
default=DEFAULT_SITE_DIR,
help='Site directory to work in [%default]')
parser.add_option('-v', '--verbose',
action='count', default=1,
help='Increase verbosity, can specify multiple times')
parser.add_option('-q', '--quiet',
action='count', default=0,
help='Decrease verbosity, can specify multiple times')
parser.add_option('-r', '--retry',
action='store_true', default=False,
help='Ask user if they want to re-run steps marked as done')
opts, args = parser.parse_args()
opts.verbose -= opts.quiet
doit(opts, args)
if __name__ == '__main__':
main()