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