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