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