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