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