xref: /petsc/config/configure.py (revision 419b1fbbb9e68f905d99c8ad83026c92d4f34467)
1#!/usr/bin/env python
2import os, sys
3import commands
4# to load ~/.pythonrc.py before inserting correct BuildSystem to path
5import user
6extraLogs = []
7petsc_arch = ''
8
9# Use en_US as language so that BuildSystem parses compiler messages in english
10if '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'
11if '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'
12
13if not hasattr(sys, 'version_info') or not sys.version_info[0] == 2 or not sys.version_info[1] >= 4:
14  print '*** You must have Python2 version 2.4 or higher to run ./configure        *****'
15  print '*          Python is easy to install for end users or sys-admin.              *'
16  print '*                  http://www.python.org/download/                            *'
17  print '*                                                                             *'
18  print '*           You CANNOT configure PETSc without Python                         *'
19  print '*   http://www.mcs.anl.gov/petsc/documentation/installation.html     *'
20  print '*******************************************************************************'
21  sys.exit(4)
22
23def check_for_option_mistakes(opts):
24  for opt in opts[1:]:
25    name = opt.split('=')[0]
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', 'size_t', 'MPI_Comm','MPI_Fint']:
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    if opt.find('=') >=0:
34      optval = opt.split('=')[1]
35      if optval == 'ifneeded':
36        raise ValueError('The option '+opt+' should probably be '+opt.replace('ifneeded', '1'));
37  return
38
39def check_for_option_changed(opts):
40# Document changes in command line options here.
41  optMap = [('c-blas-lapack','f2cblaslapack')]
42  for opt in opts[1:]:
43    optname = opt.split('=')[0].strip('-')
44    for oldname,newname in optMap:
45      if optname.find(oldname) >=0:
46        raise ValueError('The option '+opt+' should probably be '+opt.replace(oldname,newname))
47  return
48
49def check_petsc_arch(opts):
50  # If PETSC_ARCH not specified - use script name (if not configure.py)
51  global petsc_arch
52  found = 0
53  for name in opts:
54    if name.find('PETSC_ARCH=') >= 0:
55      petsc_arch=name.split('=')[1]
56      found = 1
57      break
58  # If not yet specified - use the filename of script
59  if not found:
60      filename = os.path.basename(sys.argv[0])
61      if not filename.startswith('configure') and not filename.startswith('reconfigure') and not filename.startswith('setup'):
62        petsc_arch=os.path.splitext(os.path.basename(sys.argv[0]))[0]
63        useName = 'PETSC_ARCH='+petsc_arch
64        opts.append(useName)
65  return 0
66
67def chkwinf90():
68  for arg in sys.argv:
69    if (arg.find('win32fe') >= 0 and (arg.find('f90') >=0 or arg.find('ifort') >=0)):
70      return 1
71  return 0
72
73def chkdosfiles():
74  if not os.path.exists('/usr/bin/cygcheck.exe'): return
75  if os.path.exists('.hg'):
76    (status,output) = commands.getstatusoutput('hg showconfig paths.default')
77    if not status and output: return
78  if os.path.exists('.git'):
79    (status,output) = commands.getstatusoutput('git rev-parse')
80    if not status: return
81  # cygwin - but not a hg clone - so check files in bin dir
82  (status,output) = commands.getstatusoutput('file bin/*')
83  if status:
84    print '==============================================================================='
85    print ' *** Incomplete cygwin install? command "file" not found!                    **'
86    print '==============================================================================='
87    return
88  if output.find('with CRLF line terminators') >= 0:
89    print '==============================================================================='
90    print ' *** Scripts are in DOS mode. Was winzip used instead of tar? Converting.......'
91    print '==============================================================================='
92    (status,output) = commands.getstatusoutput('dos2unix bin/*')
93    if status:
94      print '==============================================================================='
95      print ' *** Incomplete cygwin install? command "dos2unix" not found!                **'
96      print '==============================================================================='
97  return
98
99def chkcygwinlink():
100  if os.path.exists('/usr/bin/cygcheck.exe') and os.path.exists('/usr/bin/link.exe') and chkwinf90():
101      if '--ignore-cygwin-link' in sys.argv: return 0
102      print '==============================================================================='
103      print ' *** Cygwin /usr/bin/link detected! Compiles with CVF/Intel f90 can break!  **'
104      print ' *** To workarround do: "mv /usr/bin/link.exe /usr/bin/link-cygwin.exe"     **'
105      print ' *** Or to ignore this check, use configure option: --ignore-cygwin-link    **'
106      print '==============================================================================='
107      sys.exit(3)
108  return 0
109
110def chkbrokencygwin():
111  if os.path.exists('/usr/bin/cygcheck.exe'):
112    buf = os.popen('/usr/bin/cygcheck.exe -c cygwin').read()
113    if buf.find('1.5.11-1') > -1:
114      print '==============================================================================='
115      print ' *** cygwin-1.5.11-1 detected. ./configure fails with this version ***'
116      print ' *** Please upgrade to cygwin-1.5.12-1 or newer version. This can  ***'
117      print ' *** be done by running cygwin-setup, selecting "next" all the way.***'
118      print '==============================================================================='
119      sys.exit(3)
120  return 0
121
122def chkusingwindowspython():
123  if sys.platform == 'win32':
124    print '==============================================================================='
125    print ' *** Windows python detected. Please rerun ./configure with cygwin-python. ***'
126    print '==============================================================================='
127    sys.exit(3)
128  return 0
129
130def chkcygwinpython():
131  if os.path.exists('/usr/bin/cygcheck.exe') and sys.platform == 'cygwin' :
132    sys.argv.append('--useThreads=0')
133    extraLogs.append('''\
134===============================================================================
135** Cygwin-python detected. Threads do not work correctly. ***
136** Disabling thread usage for this run of ./configure *******
137===============================================================================''')
138  return 0
139
140def chkrhl9():
141  if os.path.exists('/etc/redhat-release'):
142    try:
143      file = open('/etc/redhat-release','r')
144      buf = file.read()
145      file.close()
146    except:
147      # can't read file - assume dangerous RHL9
148      buf = 'Shrike'
149    if buf.find('Shrike') > -1:
150      sys.argv.append('--useThreads=0')
151      extraLogs.append('''\
152==============================================================================
153   *** RHL9 detected. Threads do not work correctly with this distribution ***
154   ****** Disabling thread usage for this run of ./configure *********
155===============================================================================''')
156  return 0
157
158def check_broken_configure_log_links():
159  '''Sometime symlinks can get broken if the original files are deleted. Delete such broken links'''
160  import os
161  for logfile in ['configure.log','configure.log.bkp']:
162    if os.path.islink(logfile) and not os.path.isfile(logfile): os.remove(logfile)
163  return
164
165def move_configure_log(framework):
166  '''Move configure.log to PETSC_ARCH/conf - and update configure.log.bkp in both locations appropriately'''
167  global petsc_arch
168
169  if hasattr(framework,'arch'): petsc_arch = framework.arch
170  if hasattr(framework,'logName'): curr_file = framework.logName
171  else: curr_file = 'configure.log'
172
173  if petsc_arch:
174    import shutil
175    import os
176
177    # Just in case - confdir is not created
178    conf_dir = os.path.join(petsc_arch,'conf')
179    if not os.path.isdir(petsc_arch): os.mkdir(petsc_arch)
180    if not os.path.isdir(conf_dir): os.mkdir(conf_dir)
181
182    curr_bkp  = curr_file + '.bkp'
183    new_file  = os.path.join(conf_dir,curr_file)
184    new_bkp   = new_file + '.bkp'
185
186    # Keep backup in $PETSC_ARCH/conf location
187    if os.path.isfile(new_bkp): os.remove(new_bkp)
188    if os.path.isfile(new_file): os.rename(new_file,new_bkp)
189    if os.path.isfile(curr_file):
190      shutil.copyfile(curr_file,new_file)
191      os.remove(curr_file)
192    if os.path.isfile(new_file): os.symlink(new_file,curr_file)
193    # If the old bkp is using the same PETSC_ARCH/conf - then update bkp link
194    if os.path.realpath(curr_bkp) == os.path.realpath(new_file):
195      if os.path.isfile(curr_bkp): os.remove(curr_bkp)
196      if os.path.isfile(new_bkp): os.symlink(new_bkp,curr_bkp)
197  return
198
199def petsc_configure(configure_options):
200  try:
201    petscdir = os.environ['PETSC_DIR']
202    sys.path.append(os.path.join(petscdir,'bin'))
203    import petscnagupgrade
204    file     = os.path.join(petscdir,'.nagged')
205    if not petscnagupgrade.naggedtoday(file):
206      petscnagupgrade.currentversion(petscdir)
207  except:
208    pass
209  print '==============================================================================='
210  print '             Configuring PETSc to compile on your system                       '
211  print '==============================================================================='
212
213  try:
214    # Command line arguments take precedence (but don't destroy argv[0])
215    sys.argv = sys.argv[:1] + configure_options + sys.argv[1:]
216    check_for_option_mistakes(sys.argv)
217    check_for_option_changed(sys.argv)
218  except (TypeError, ValueError), e:
219    emsg = str(e)
220    if not emsg.endswith('\n'): emsg = emsg+'\n'
221    msg ='*******************************************************************************\n'\
222    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
223    +'-------------------------------------------------------------------------------\n'  \
224    +emsg+'*******************************************************************************\n'
225    sys.exit(msg)
226  # check PETSC_ARCH
227  check_petsc_arch(sys.argv)
228  check_broken_configure_log_links()
229
230  # support a few standard configure option types
231  for l in range(0,len(sys.argv)):
232    name = sys.argv[l]
233    if name.find('enable-') >= 0:
234      if name.find('=') == -1:
235        sys.argv[l] = name.replace('enable-','with-')+'=1'
236      else:
237        head, tail = name.split('=', 1)
238        sys.argv[l] = head.replace('enable-','with-')+'='+tail
239    if name.find('disable-') >= 0:
240      if name.find('=') == -1:
241        sys.argv[l] = name.replace('disable-','with-')+'=0'
242      else:
243        head, tail = name.split('=', 1)
244        if tail == '1': tail = '0'
245        sys.argv[l] = head.replace('disable-','with-')+'='+tail
246    if name.find('without-') >= 0:
247      if name.find('=') == -1:
248        sys.argv[l] = name.replace('without-','with-')+'=0'
249      else:
250        head, tail = name.split('=', 1)
251        if tail == '1': tail = '0'
252        sys.argv[l] = head.replace('without-','with-')+'='+tail
253
254  # Check for broken cygwin
255  chkbrokencygwin()
256  # Disable threads on RHL9
257  chkrhl9()
258  # Make sure cygwin-python is used on windows
259  chkusingwindowspython()
260  # Threads don't work for cygwin & python...
261  chkcygwinpython()
262  chkcygwinlink()
263  chkdosfiles()
264
265  # Should be run from the toplevel
266  configDir = os.path.abspath('config')
267  bsDir     = os.path.join(configDir, 'BuildSystem')
268  if not os.path.isdir(configDir):
269    raise RuntimeError('Run configure from $PETSC_DIR, not '+os.path.abspath('.'))
270  sys.path.insert(0, bsDir)
271  sys.path.insert(0, configDir)
272  import config.base
273  import config.framework
274  import cPickle
275
276  framework = None
277  try:
278    framework = config.framework.Framework(['--configModules=PETSc.Configure','--optionsModule=PETSc.compilerOptions']+sys.argv[1:], loadArgDB = 0)
279    framework.setup()
280    framework.logPrint('\n'.join(extraLogs))
281    framework.configure(out = sys.stdout)
282    framework.storeSubstitutions(framework.argDB)
283    framework.argDB['configureCache'] = cPickle.dumps(framework)
284    framework.printSummary()
285    framework.argDB.save(force = True)
286    framework.logClear()
287    framework.closeLog()
288    try:
289      move_configure_log(framework)
290    except:
291      # perhaps print an error about unable to shuffle logs?
292      pass
293    return 0
294  except (RuntimeError, config.base.ConfigureSetupError), e:
295    emsg = str(e)
296    if not emsg.endswith('\n'): emsg = emsg+'\n'
297    msg ='*******************************************************************************\n'\
298    +'         UNABLE to CONFIGURE with GIVEN OPTIONS    (see configure.log for details):\n' \
299    +'-------------------------------------------------------------------------------\n'  \
300    +emsg+'*******************************************************************************\n'
301    se = ''
302  except (TypeError, ValueError), e:
303    emsg = str(e)
304    if not emsg.endswith('\n'): emsg = emsg+'\n'
305    msg ='*******************************************************************************\n'\
306    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
307    +'-------------------------------------------------------------------------------\n'  \
308    +emsg+'*******************************************************************************\n'
309    se = ''
310  except ImportError, e :
311    emsg = str(e)
312    if not emsg.endswith('\n'): emsg = emsg+'\n'
313    msg ='*******************************************************************************\n'\
314    +'                     UNABLE to FIND MODULE for ./configure \n' \
315    +'-------------------------------------------------------------------------------\n'  \
316    +emsg+'*******************************************************************************\n'
317    se = ''
318  except OSError, e :
319    emsg = str(e)
320    if not emsg.endswith('\n'): emsg = emsg+'\n'
321    msg ='*******************************************************************************\n'\
322    +'                    UNABLE to EXECUTE BINARIES for ./configure \n' \
323    +'-------------------------------------------------------------------------------\n'  \
324    +emsg+'*******************************************************************************\n'
325    se = ''
326  except SystemExit, e:
327    if e.code is None or e.code == 0:
328      return
329    msg ='*******************************************************************************\n'\
330    +'         CONFIGURATION FAILURE  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
331    +'*******************************************************************************\n'
332    se  = str(e)
333  except Exception, e:
334    msg ='*******************************************************************************\n'\
335    +'        CONFIGURATION CRASH  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
336    +'*******************************************************************************\n'
337    se  = str(e)
338
339  print msg
340  if not framework is None:
341    framework.logClear()
342    if hasattr(framework, 'log'):
343      try:
344        if hasattr(framework,'compilerDefines'):
345          framework.log.write('**** Configure header '+framework.compilerDefines+' ****\n')
346          framework.outputHeader(framework.log)
347        if hasattr(framework,'compilerFixes'):
348          framework.log.write('**** C specific Configure header '+framework.compilerFixes+' ****\n')
349          framework.outputCHeader(framework.log)
350      except Exception, e:
351        framework.log.write('Problem writing headers to log: '+str(e))
352      import traceback
353      try:
354        framework.log.write(msg+se)
355        traceback.print_tb(sys.exc_info()[2], file = framework.log)
356        if hasattr(framework,'log'): framework.log.close()
357        move_configure_log(framework)
358      except:
359        pass
360      sys.exit(1)
361  else:
362    print se
363    import traceback
364    traceback.print_tb(sys.exc_info()[2])
365  if hasattr(framework,'log'): framework.log.close()
366
367if __name__ == '__main__':
368  petsc_configure([])
369
370