/
loc_bld_tst.py
436 lines (363 loc) · 14.3 KB
/
loc_bld_tst.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
import codecs
import os
import shlex
import shutil
import subprocess
import sys
import tarfile
import time
import urllib2
def get_file(url):
"""Copies the specified file into the current directory, whether
the file is local or remote.
"""
fname = os.path.basename(url)
if url.startswith('http'):
resp = urllib2.urlopen(url)
gofile = open(fname, 'wb')
shutil.copyfileobj(resp.fp, gofile)
gofile.close()
else: # file is in local file system
if not os.path.isfile(url):
print "Can't find file '%s'" % url
sys.exit(-1)
if os.path.dirname(url) != os.getcwd():
shutil.copy(url, fname)
return fname
def _run_gofile(startdir, gopath, args=()):
retcode = -1
godir, gofile = os.path.split(gopath)
os.chdir(godir)
outname = 'build.out'
f = open(outname, 'wb')
py = sys.executable.replace('\\','/')
envdict = os.environ.copy()
# if we're running from inside of a virtualenv, we need to
# remove VIRTUAL_ENV from the environment before spawning the
# subprocess, else the build will end up inside of devenv
# instead of where it's supposed to be
if 'VIRTUAL_ENV' in envdict:
del envdict['VIRTUAL_ENV']
try:
p = subprocess.Popen('%s %s %s' % (py, gofile, ' '.join(args)),
stdout=f, stderr=subprocess.STDOUT,
shell=True, env=envdict)
_wait(p)
retcode = p.returncode
finally:
f.close()
# in some cases there are some unicode characters in the
# output which cause fabric to barf, so strip out unicode
# before returning
if sys.platform.startswith('win'):
mode = 'r'
else:
mode = 'rt'
with codecs.open(outname, mode, encoding='ascii', errors='ignore') as f:
for line in f:
print line,
sys.stdout.flush()
os.chdir(startdir)
return retcode
def _run_install_script(startdir, install_script_path, args=()):
import os
retcode = -1
install_script_dir, install_script_file = os.path.split(install_script_path)
os.chdir(install_script_dir)
outname = 'build.out'
f = open(outname, 'wb')
py = sys.executable.replace('\\','/')
envdict = os.environ.copy()
# if we're running from inside of a virtualenv, we need to
# remove VIRTUAL_ENV from the environment before spawning the
# subprocess, else the build will end up inside of devenv
# instead of where it's supposed to be
# if 'VIRTUAL_ENV' in envdict:
# del envdict['VIRTUAL_ENV']
try:
print 'running install script with', '%s %s %s' % (py, install_script_file, ' '.join(args))
p = subprocess.Popen('%s %s %s' % (py, install_script_file, ' '.join(args)),
stdout=f, stderr=subprocess.STDOUT,
shell=True, env=envdict)
_wait(p)
retcode = p.returncode
finally:
f.close()
# in some cases there are some unicode characters in the
# output which cause fabric to barf, so strip out unicode
# before returning
if sys.platform.startswith('win'):
mode = 'r'
else:
mode = 'rt'
with codecs.open(outname, mode, encoding='ascii', errors='ignore') as f:
for line in f:
print line,
sys.stdout.flush()
os.chdir(startdir)
return retcode
def _run_sub(outname, cmd, env=None):
f = open(outname, 'wb')
try:
if sys.platform.startswith('win'):
p = subprocess.Popen(cmd, stdout=f, stderr=subprocess.STDOUT,
shell=True, env=env)
else:
p = subprocess.Popen(cmd, stdout=f, stderr=subprocess.STDOUT,
shell=True, env=env, executable='/bin/bash')
_wait(p)
finally:
f.close()
# in some cases there are some unicode characters in the
# output which cause fabric to barf, so strip out unicode
# before returning
if sys.platform.startswith('win'):
mode = 'r'
else:
mode = 'rt'
with codecs.open(outname, mode, encoding='ascii', errors='ignore') as f:
for line in f:
print line,
sys.stdout.flush()
return p.returncode
def _wait(p):
""" To avoid firewall inactivity timeouts, print while waiting. """
# Using 'keepalive' options in fabric or paramiko did not fix this problem.
print 'process launched...'
sys.stdout.flush()
start = time.time()
while p.returncode is None:
if p.poll() is not None:
break
else:
time.sleep(10)
if time.time() - start >= 10 * 60:
print 'waiting for process to finish...'
sys.stdout.flush()
start = time.time()
def build_and_test(fname=None, workdir='.', keep=False,
branch=None, anaconda=False, mpi=False, testargs=()):
"""Builds OpenMDAO, either a dev build or a release build, and runs
the test suite on it.
"""
if fname is None:
raise RuntimeError("build_and_test: missing arg 'fname'")
if not fname.startswith('http'):
fname = os.path.abspath(fname)
workdir = os.path.abspath(workdir)
startdir = os.getcwd()
if fname.endswith('.py'):
build_type = 'release'
else:
build_type = 'dev'
args = ['-f', fname]
if branch:
args.append('--branch=%s' % branch)
os.chdir(workdir)
print 'building...'
sys.stdout.flush()
try:
if build_type == 'release':
envdir, retcode = install_release(fname)
else: # dev test
envdir, retcode = install_dev_env(fname, branch=branch, anaconda=anaconda)
finally:
os.chdir(workdir)
print "build return code =", retcode
sys.stdout.flush()
if retcode != 0:
sys.exit(retcode)
if build_type == 'release':
for arg in testargs:
if not arg.startswith('-'):
break
else:
if '--small' not in testargs and '--all' not in testargs:
testargs.append('--all') # otherwise release test runs small set by default
print '\ntesting (testargs=%s) ...' % testargs
sys.stdout.flush()
try:
retcode = activate_and_test(envdir, testargs,anaconda=anaconda, mpi=mpi)
print "test return code =", retcode
finally:
sys.stdout.flush()
os.chdir(startdir)
return retcode
def install_release(url):
"""
Installs an OpenMDAO release in the current directory.
url: str
The url of the go-openmdao-???.py file.
Returns the name of the newly built release directory.
"""
gofile = get_file(url)
if not os.path.basename(gofile).startswith('go-openmdao-'):
print "Name of OpenMDAO bootstrapping script must be 'go-openmdao-<version>.py',",
print " not '%s'" % os.path.basename(gofile)
sys.exit(-1)
# parse pathname to find dists dir
dn = os.path.dirname
dpath = os.path.join(dn(dn(dn(url))), 'dists')
args = []
if os.path.isdir(dpath):
args.append('--testurl=%s' % dpath)
print "building openmdao environment [%s]" % ' '.join(args)
startdir = os.getcwd()
dirfiles = set(os.listdir('.'))
retcode = _run_gofile(startdir, os.path.join(startdir, gofile), args)
newfiles = set(os.listdir('.')) - dirfiles - set(['build.out', 'openmdao_log.txt'])
if len(newfiles) != 1:
raise RuntimeError("didn't expect %s in build directory" %
list(newfiles))
releasedir = os.path.join(startdir, newfiles.pop())
return (releasedir, retcode)
def install_dev_env(url, branch=None, anaconda=False):
"""
Installs an OpenMDAO dev environment given an OpenMDAO source
tree.
url: str
URL of tarfile or Git repo containing an OpenMDAO source tree. May be
a local file path or an actual URL.
branch: str
For Git repos, branch name must be supplied.
"""
startdir = os.getcwd()
# make sure we don't clobber an existing repo
if os.path.exists('OpenMDAO-Framework'):
print "Directory OpenMDAO-Framework already exists"
sys.exit(-1)
if url.endswith('.git'): # clone the git repo
if branch is None:
print "You must supply a branch name for a git repo"
sys.exit(-1)
dirfiles = set(os.listdir('.'))
print "cloning git repo at %s" % url
subprocess.check_call(["git", "clone", url])
base = os.path.basename(url)
if base == '.git':
treedir = os.path.dirname(url)
else:
treedir = os.path.splitext(os.path.basename(url))[0]
treedir = os.path.abspath(treedir)
os.chdir(treedir)
try:
subprocess.check_call(['git', 'checkout', options.branch])
finally:
os.chdir(startdir)
elif url.endswith('.tar.gz') or url.endswith('.tar'):
tarpath = get_file(url)
dirfiles = set(os.listdir('.'))
tar = tarfile.open(tarpath)
tar.extractall()
tar.close()
else:
raise RuntimeError("url '%s' does not end in"
" '.git' or '.tar.gz' or '.tar'" % url)
newfiles = set(os.listdir('.')) - dirfiles
if len(newfiles) != 1:
raise RuntimeError("didn't expect %s in build directory" %
list(newfiles))
treedir = newfiles.pop()
print "building openmdao development environment in %s" % treedir
install_script_path = os.path.join(treedir, 'install_openmdao_dev.py')
retcode = _run_install_script(startdir, install_script_path)
if anaconda:
envdir = treedir
else:
envdir = os.path.join(treedir, 'devenv')
print 'new openmdao environment built in %s' % envdir
return (envdir, retcode)
def activate_and_test(envdir, testargs=(), anaconda=False, mpi=False):
"""
Runs the test suite on an OpenMDAO virtual environment located
in the specified directory.
Returns the return code of the process that runs the test suite.
"""
if anaconda:
if sys.platform.startswith('win'):
command = 'activate openmdao-dev && openmdao test %s' % ' '.join(testargs)
else:
command = 'source activate openmdao-dev && openmdao test %s 2>&1 | tee ../test.out' \
% ' '.join(testargs)
# activate the environment and run tests
# devbinpath = os.path.join(envdir, devbindir)
os.chdir(envdir)
print "running tests from %s" % envdir
# print "running tests from %s" % devbinpath
env = os.environ.copy()
print "command = ", command
return _run_sub('test.out', command, env=env)
elif mpi:
#Runs the mpi test suite using testflo
#Returns the return code of the process
#that runs the test suite.
if sys.platform.startswith('win'):
devbindir = 'Scripts'
act_cmd = 'activate.bat'
else:
devbindir = 'bin'
act_cmd = '. ./activate'
devbinpath = os.path.join(envdir, devbindir)
os.chdir(devbinpath)
env = os.environ.copy()
for name in ['VIRTUAL_ENV', '_OLD_VIRTUAL_PATH', '_OLD_VIRTUAL_PROMPT']:
if name in env:
del env[name]
#Do everything in one big command, because issuing separate ones clones new shells,
#in which we are not activated nor in the same dir.
command = act_cmd + " && cd ../.. && git clone http://github.com/naylor-b/testflo.git && cd testflo && python setup.py install && cd .. && testflo -i contrib/testmpi"
print "command = ", command
return _run_sub('activate_and_test.out', command, env=env)
else:
if sys.platform.startswith('win'):
devbindir = 'Scripts'
command = 'activate.bat && openmdao test %s' % ' '.join(testargs)
else:
devbindir = 'bin'
command = '. ./activate && openmdao test %s 2>&1 | tee ../../test.out' \
% ' '.join(testargs)
# activate the environment and run tests
devbinpath = os.path.join(envdir, devbindir)
os.chdir(devbinpath)
print "running tests from %s" % devbinpath
env = os.environ.copy()
for name in ['VIRTUAL_ENV', '_OLD_VIRTUAL_PATH', '_OLD_VIRTUAL_PROMPT']:
if name in env:
del env[name]
print "command = ", command
return _run_sub('test.out', command, env=env)
if __name__ == '__main__':
from optparse import OptionParser
parser = OptionParser(usage="%prog [OPTIONS]")
parser.add_option("--branch", action="store", type='string',
dest='branch',
help="if file_url is a git repo, supply branch name here")
parser.add_option("-f", "--file", action="store", type='string',
dest='fname',
help="pathname or URL of a git repo, tar file,"
" or go-openmdao-<version>.py file")
parser.add_option("-d", "--dir", action="store", type='string',
dest='directory', default='.',
help="name of a directory the build will be created in")
parser.add_option("--testargs", action="store", type='string',
dest='testargs', default='',
help="args to pass to openmdao test")
parser.add_option("--anaconda", action="store_true", dest="anaconda", default=False)
parser.add_option("--mpi", action="store_true", dest="mpi", default=False)
# Handle quoting problem that happens on Windows (at least).
# (--testargs="-v --gui" gets split into: '--testargs="-v', '--gui', '"')
args = []
i = 1
while i < len(sys.argv):
arg = sys.argv[i]
i += 1
while arg.count('"') == 1 and i < len(sys.argv):
next_arg = sys.argv[i]
i += 1
arg += ' '+next_arg
args.append(arg)
(options, args) = parser.parse_args(args)
sys.exit(build_and_test(fname=options.fname, workdir=options.directory,
branch=options.branch,anaconda=options.anaconda,
mpi=options.mpi,
testargs=shlex.split(options.testargs)))