xref: /petsc/config/configure.py (revision db31f6defe33e3dfd9985704e6b8f54a7ffb6553)
1#!/usr/bin/env python
2import os, sys
3import commands
4# to load ~/.pythonrc.py before inserting correct BuildSystem to path
5import user
6extraLogs = []
7petsc_arch = ''
8
9import urllib
10import tarfile
11
12def untar(tar, path = '.', leading = ''):
13  if leading:
14    entries = [t.name for t in tar.getmembers()]
15    prefix = os.path.commonprefix(entries)
16    if prefix:
17      for tarinfo in tar.getmembers():
18        tail = tarinfo.name.split(prefix, 1)[1]
19        tarinfo.name = os.path.join(leading, tail)
20  for tarinfo in tar.getmembers():
21    tar.extract(tarinfo, path)
22  return
23
24def downloadPackage(url, filename, targetDirname):
25  '''Download the tarball for a package at url, save it as filename, and untar it into targetDirname'''
26  filename, headers = urllib.urlretrieve(url, filename)
27  tar = tarfile.open(filename, 'r:gz')
28  untar(tar, targetDirname, leading = filename.split('.')[0])
29  return
30
31def getBuildSystem(configDir,bsDir):
32  print '==============================================================================='
33  print '''++ Could not locate BuildSystem in %s.''' % configDir
34  (status,output) = commands.getstatusoutput('hg showconfig paths.default')
35  if status or not output:
36    print '++ Mercurial clone not found. Downloading it from http://petsc.cs.iit.edu/petsc/BuildSystem/archive/tip.tar.gz'
37    downloadPackage('http://petsc.cs.iit.edu/petsc/BuildSystem/archive/tip.tar.gz', 'BuildSystem.tar.gz', configDir)
38  else:
39    print '++ Mercurial clone found. URL : ' + output
40    bsurl = output.replace('petsc-dev','BuildSystem').replace('releases/petsc-','releases/BuildSystem-')
41    if bsurl.find('bitbucket.org') >=0: bsurl = bsurl.lower()
42    print '++ Using: hg clone '+ bsurl +' '+ bsDir
43    (status,output) = commands.getstatusoutput('hg clone '+ bsurl +' '+ bsDir)
44    if status:
45      print '++ Unable to clone BuildSystem. Please clone manually'
46      print '==============================================================================='
47      sys.exit(3)
48  print '==============================================================================='
49  return
50
51
52# Use en_US as language so that BuildSystem parses compiler messages in english
53if 'LC_LOCAL' in os.environ and os.environ['LC_LOCAL'] != '' and os.environ['LC_LOCAL'] != 'en_US' and os.environ['LC_LOCAL']!= 'en_US.UTF-8': os.environ['LC_LOCAL'] = 'en_US.UTF-8'
54if 'LANG' in os.environ and os.environ['LANG'] != '' and os.environ['LANG'] != 'en_US' and os.environ['LANG'] != 'en_US.UTF-8': os.environ['LANG'] = 'en_US.UTF-8'
55
56if not hasattr(sys, 'version_info') or not sys.version_info[0] == 2 or not sys.version_info[1] >= 4:
57  print '*** You must have Python2 version 2.4 or higher to run ./configure        *****'
58  print '*          Python is easy to install for end users or sys-admin.              *'
59  print '*                  http://www.python.org/download/                            *'
60  print '*                                                                             *'
61  print '*           You CANNOT configure PETSc without Python                         *'
62  print '*   http://www.mcs.anl.gov/petsc/documentation/installation.html     *'
63  print '*******************************************************************************'
64  sys.exit(4)
65
66def check_for_option_mistakes(opts):
67  for opt in opts[1:]:
68    name = opt.split('=')[0]
69    if name.find('_') >= 0:
70      exception = False
71      for exc in ['superlu_dist', 'PETSC_ARCH', 'PETSC_DIR', 'CXX_CXXFLAGS', 'LD_SHARED', 'CC_LINKER_FLAGS', 'CXX_LINKER_FLAGS', 'FC_LINKER_FLAGS', 'AR_FLAGS', 'C_VERSION', 'CXX_VERSION', 'FC_VERSION', 'size_t', 'MPI_Comm','MPI_Fint']:
72        if name.find(exc) >= 0:
73          exception = True
74      if not exception:
75        raise ValueError('The option '+name+' should probably be '+name.replace('_', '-'));
76    if opt.find('=') >=0:
77      optval = opt.split('=')[1]
78      if optval == 'ifneeded':
79        raise ValueError('The option '+opt+' should probably be '+opt.replace('ifneeded', '1'));
80  return
81
82def check_for_option_changed(opts):
83# Document changes in command line options here.
84  optMap = [('c-blas-lapack','f2cblaslapack')]
85  for opt in opts[1:]:
86    optname = opt.split('=')[0].strip('-')
87    for oldname,newname in optMap:
88      if optname.find(oldname) >=0:
89        raise ValueError('The option '+opt+' should probably be '+opt.replace(oldname,newname))
90  return
91
92def check_petsc_arch(opts):
93  # If PETSC_ARCH not specified - use script name (if not configure.py)
94  global petsc_arch
95  found = 0
96  for name in opts:
97    if name.find('PETSC_ARCH=') >= 0:
98      petsc_arch=name.split('=')[1]
99      found = 1
100      break
101  # If not yet specified - use the filename of script
102  if not found:
103      filename = os.path.basename(sys.argv[0])
104      if not filename.startswith('configure') and not filename.startswith('reconfigure') and not filename.startswith('setup'):
105        petsc_arch=os.path.splitext(os.path.basename(sys.argv[0]))[0]
106        useName = 'PETSC_ARCH='+petsc_arch
107        opts.append(useName)
108  return 0
109
110def chkwinf90():
111  for arg in sys.argv:
112    if (arg.find('win32fe') >= 0 and (arg.find('f90') >=0 or arg.find('ifort') >=0)):
113      return 1
114  return 0
115
116def chkcygwinlink():
117  if os.path.exists('/usr/bin/cygcheck.exe') and os.path.exists('/usr/bin/link.exe') and chkwinf90():
118      if '--ignore-cygwin-link' in sys.argv: return 0
119      print '==============================================================================='
120      print ' *** Cygwin /usr/bin/link detected! Compiles with CVF/Intel f90 can break!  **'
121      print ' *** To workarround do: "mv /usr/bin/link.exe /usr/bin/link-cygwin.exe"     **'
122      print ' *** Or to ignore this check, use configure option: --ignore-cygwin-link    **'
123      print '==============================================================================='
124      sys.exit(3)
125  return 0
126
127def chkbrokencygwin():
128  if os.path.exists('/usr/bin/cygcheck.exe'):
129    buf = os.popen('/usr/bin/cygcheck.exe -c cygwin').read()
130    if buf.find('1.5.11-1') > -1:
131      print '==============================================================================='
132      print ' *** cygwin-1.5.11-1 detected. ./configure fails with this version ***'
133      print ' *** Please upgrade to cygwin-1.5.12-1 or newer version. This can  ***'
134      print ' *** be done by running cygwin-setup, selecting "next" all the way.***'
135      print '==============================================================================='
136      sys.exit(3)
137  return 0
138
139def chkcygwinpython():
140  if os.path.exists('/usr/bin/cygcheck.exe') and sys.platform == 'cygwin' :
141    sys.argv.append('--useThreads=0')
142    extraLogs.append('''\
143===============================================================================
144** Cygwin-python detected. Threads do not work correctly. ***
145** Disabling thread usage for this run of ./configure *******
146===============================================================================''')
147  return 0
148
149def chkrhl9():
150  if os.path.exists('/etc/redhat-release'):
151    try:
152      file = open('/etc/redhat-release','r')
153      buf = file.read()
154      file.close()
155    except:
156      # can't read file - assume dangerous RHL9
157      buf = 'Shrike'
158    if buf.find('Shrike') > -1:
159      sys.argv.append('--useThreads=0')
160      extraLogs.append('''\
161==============================================================================
162   *** RHL9 detected. Threads do not work correctly with this distribution ***
163   ****** Disabling thread usage for this run of ./configure *********
164===============================================================================''')
165  return 0
166
167def check_broken_configure_log_links():
168  '''Sometime symlinks can get broken if the original files are deleted. Delete such broken links'''
169  import os
170  for logfile in ['configure.log','configure.log.bkp']:
171    if os.path.islink(logfile) and not os.path.isfile(logfile): os.remove(logfile)
172  return
173
174def move_configure_log(framework):
175  '''Move configure.log to PETSC_ARCH/conf - and update configure.log.bkp in both locations appropriately'''
176  global petsc_arch
177
178  if hasattr(framework,'arch'): petsc_arch = framework.arch
179  if hasattr(framework,'logName'): curr_file = framework.logName
180  else: curr_file = 'configure.log'
181
182  if petsc_arch:
183    import shutil
184    import os
185
186    # Just in case - confdir is not created
187    conf_dir = os.path.join(petsc_arch,'conf')
188    if not os.path.isdir(petsc_arch): os.mkdir(petsc_arch)
189    if not os.path.isdir(conf_dir): os.mkdir(conf_dir)
190
191    curr_bkp  = curr_file + '.bkp'
192    new_file  = os.path.join(conf_dir,curr_file)
193    new_bkp   = new_file + '.bkp'
194
195    # Keep backup in $PETSC_ARCH/conf location
196    if os.path.isfile(new_bkp): os.remove(new_bkp)
197    if os.path.isfile(new_file): os.rename(new_file,new_bkp)
198    if os.path.isfile(curr_file):
199      shutil.copyfile(curr_file,new_file)
200      os.remove(curr_file)
201    if os.path.isfile(new_file): os.symlink(new_file,curr_file)
202    # If the old bkp is using the same PETSC_ARCH/conf - then update bkp link
203    if os.path.realpath(curr_bkp) == os.path.realpath(new_file):
204      if os.path.isfile(curr_bkp): os.remove(curr_bkp)
205      if os.path.isfile(new_bkp): os.symlink(new_bkp,curr_bkp)
206  return
207
208def petsc_configure(configure_options):
209  try:
210    petscdir = os.environ['PETSC_DIR']
211    sys.path.append(os.path.join(petscdir,'bin'))
212    import petscnagupgrade
213    file     = os.path.join(petscdir,'.nagged')
214    if not petscnagupgrade.naggedtoday(file):
215      petscnagupgrade.currentversion(petscdir)
216  except:
217    pass
218  print '==============================================================================='
219  print '             Configuring PETSc to compile on your system                       '
220  print '==============================================================================='
221
222  try:
223    # Command line arguments take precedence (but don't destroy argv[0])
224    sys.argv = sys.argv[:1] + configure_options + sys.argv[1:]
225    check_for_option_mistakes(sys.argv)
226    check_for_option_changed(sys.argv)
227  except (TypeError, ValueError), e:
228    emsg = str(e)
229    if not emsg.endswith('\n'): emsg = emsg+'\n'
230    msg ='*******************************************************************************\n'\
231    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
232    +'-------------------------------------------------------------------------------\n'  \
233    +emsg+'*******************************************************************************\n'
234    sys.exit(msg)
235  # check PETSC_ARCH
236  check_petsc_arch(sys.argv)
237  check_broken_configure_log_links()
238
239  # support a few standard configure option types
240  for l in range(0,len(sys.argv)):
241    name = sys.argv[l]
242    if name.find('enable-') >= 0:
243      if name.find('=') == -1:
244        sys.argv[l] = name.replace('enable-','with-')+'=1'
245      else:
246        head, tail = name.split('=', 1)
247        sys.argv[l] = head.replace('enable-','with-')+'='+tail
248    if name.find('disable-') >= 0:
249      if name.find('=') == -1:
250        sys.argv[l] = name.replace('disable-','with-')+'=0'
251      else:
252        head, tail = name.split('=', 1)
253        if tail == '1': tail = '0'
254        sys.argv[l] = head.replace('disable-','with-')+'='+tail
255    if name.find('without-') >= 0:
256      if name.find('=') == -1:
257        sys.argv[l] = name.replace('without-','with-')+'=0'
258      else:
259        head, tail = name.split('=', 1)
260        if tail == '1': tail = '0'
261        sys.argv[l] = head.replace('without-','with-')+'='+tail
262
263  # Check for broken cygwin
264  chkbrokencygwin()
265  # Disable threads on RHL9
266  chkrhl9()
267  # Threads don't work for cygwin & python...
268  chkcygwinpython()
269  chkcygwinlink()
270
271  # Should be run from the toplevel
272  configDir = os.path.abspath('config')
273  bsDir     = os.path.join(configDir, 'BuildSystem')
274  if not os.path.isdir(configDir):
275    raise RuntimeError('Run configure from $PETSC_DIR, not '+os.path.abspath('.'))
276  if not os.path.isdir(bsDir): getBuildSystem(configDir,bsDir)
277  sys.path.insert(0, bsDir)
278  sys.path.insert(0, configDir)
279  import config.base
280  import config.framework
281  import cPickle
282
283  framework = None
284  try:
285    framework = config.framework.Framework(['--configModules=PETSc.Configure','--optionsModule=PETSc.compilerOptions']+sys.argv[1:], loadArgDB = 0)
286    framework.setup()
287    framework.logPrint('\n'.join(extraLogs))
288    framework.configure(out = sys.stdout)
289    framework.storeSubstitutions(framework.argDB)
290    framework.argDB['configureCache'] = cPickle.dumps(framework)
291    framework.printSummary()
292    framework.argDB.save(force = True)
293    framework.logClear()
294    framework.closeLog()
295    try:
296      move_configure_log(framework)
297    except:
298      # perhaps print an error about unable to shuffle logs?
299      pass
300    return 0
301  except (RuntimeError, config.base.ConfigureSetupError), e:
302    emsg = str(e)
303    if not emsg.endswith('\n'): emsg = emsg+'\n'
304    msg ='*******************************************************************************\n'\
305    +'         UNABLE to CONFIGURE with GIVEN OPTIONS    (see configure.log for details):\n' \
306    +'-------------------------------------------------------------------------------\n'  \
307    +emsg+'*******************************************************************************\n'
308    se = ''
309  except (TypeError, ValueError), e:
310    emsg = str(e)
311    if not emsg.endswith('\n'): emsg = emsg+'\n'
312    msg ='*******************************************************************************\n'\
313    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
314    +'-------------------------------------------------------------------------------\n'  \
315    +emsg+'*******************************************************************************\n'
316    se = ''
317  except ImportError, e :
318    emsg = str(e)
319    if not emsg.endswith('\n'): emsg = emsg+'\n'
320    msg ='*******************************************************************************\n'\
321    +'                     UNABLE to FIND MODULE for ./configure \n' \
322    +'-------------------------------------------------------------------------------\n'  \
323    +emsg+'*******************************************************************************\n'
324    se = ''
325  except OSError, e :
326    emsg = str(e)
327    if not emsg.endswith('\n'): emsg = emsg+'\n'
328    msg ='*******************************************************************************\n'\
329    +'                    UNABLE to EXECUTE BINARIES for ./configure \n' \
330    +'-------------------------------------------------------------------------------\n'  \
331    +emsg+'*******************************************************************************\n'
332    se = ''
333  except SystemExit, e:
334    if e.code is None or e.code == 0:
335      return
336    msg ='*******************************************************************************\n'\
337    +'         CONFIGURATION FAILURE  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
338    +'*******************************************************************************\n'
339    se  = str(e)
340  except Exception, e:
341    msg ='*******************************************************************************\n'\
342    +'        CONFIGURATION CRASH  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
343    +'*******************************************************************************\n'
344    se  = str(e)
345
346  print msg
347  if not framework is None:
348    framework.logClear()
349    if hasattr(framework, 'log'):
350      try:
351        framework.log.write('**** Configure header conftest.h ****\n')
352        framework.outputHeader(framework.log)
353        framework.log.write('**** C specific Configure header conffix.h ****\n')
354        framework.outputCHeader(framework.log)
355      except Exception, e:
356        framework.log.write('Problem writing headers to log: '+str(e))
357      import traceback
358      try:
359        framework.log.write(msg+se)
360        traceback.print_tb(sys.exc_info()[2], file = framework.log)
361        if hasattr(framework,'log'): framework.log.close()
362        move_configure_log(framework)
363      except:
364        pass
365      sys.exit(1)
366  else:
367    print se
368    import traceback
369    traceback.print_tb(sys.exc_info()[2])
370  if hasattr(framework,'log'): framework.log.close()
371
372if __name__ == '__main__':
373  petsc_configure([])
374
375