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