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