xref: /petsc/config/configure.py (revision a7fac7c2b47dbcd8ece0cc2dfdfe0e63be1bb7b5)
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 ['mkl_cpardiso', 'mkl_pardiso', 'superlu_dist', 'superlu_mt', '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','int64_t']:
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 = [('with-64bit-indices','with-64-bit-indices'),('c-blas-lapack','f2cblaslapack'),('cholmod','suitesparse'),('umfpack','suitesparse'),('f-blas-lapack','fblaslapack')]
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 chkenable():
68  #Replace all 'enable-'/'disable-' with 'with-'=0/1/tail
69  #enable-fortran is a special case, the resulting --with-fortran is ambiguous.
70  #Would it mean --with-fc= or --with-fortran-interfaces=?
71  for l in range(0,len(sys.argv)):
72    name = sys.argv[l]
73    if name.find('enable-fortran') >= 0:
74      if name.find('=') == -1:
75        sys.argv[l] = name.replace('enable-fortran','with-fortran-interfaces')+'=1'
76      else:
77        head, tail = name.split('=', 1)
78        sys.argv[l] = head.replace('enable-fortran','with-fortran-interfaces')+'='+tail
79      continue
80    if name.find('disable-fortran') >= 0:
81      if name.find('=') == -1:
82        sys.argv[l] = name.replace('disable-fortran','with-fortran-interfaces')+'=0'
83      else:
84        head, tail = name.split('=', 1)
85        if tail == '1': tail = '0'
86        sys.argv[l] = head.replace('disable-fortran','with-fortran-interfaces')+'='+tail
87      continue
88
89    if name.find('enable-cxx') >= 0:
90      if name.find('=') == -1:
91        sys.argv[l] = name.replace('enable-cxx','with-clanguage=C++')
92      else:
93        head, tail = name.split('=', 1)
94        if tail=='0':
95          sys.argv[l] = head.replace('enable-cxx','with-clanguage=C')
96        else:
97          sys.argv[l] = head.replace('enable-cxx','with-clanguage=C++')
98      continue
99    if name.find('disable-cxx') >= 0:
100      if name.find('=') == -1:
101        sys.argv[l] = name.replace('disable-cxx','with-clanguage=C')
102      else:
103        head, tail = name.split('=', 1)
104        if tail == '0':
105          sys.argv[l] = head.replace('disable-cxx','with-clanguage=C++')
106        else:
107          sys.argv[l] = head.replace('disable-cxx','with-clanguage=C')
108      continue
109
110
111    if name.find('enable-') >= 0:
112      if name.find('=') == -1:
113        sys.argv[l] = name.replace('enable-','with-')+'=1'
114      else:
115        head, tail = name.split('=', 1)
116        sys.argv[l] = head.replace('enable-','with-')+'='+tail
117    if name.find('disable-') >= 0:
118      if name.find('=') == -1:
119        sys.argv[l] = name.replace('disable-','with-')+'=0'
120      else:
121        head, tail = name.split('=', 1)
122        if tail == '1': tail = '0'
123        sys.argv[l] = head.replace('disable-','with-')+'='+tail
124    if name.find('without-') >= 0:
125      if name.find('=') == -1:
126        sys.argv[l] = name.replace('without-','with-')+'=0'
127      else:
128        head, tail = name.split('=', 1)
129        if tail == '1': tail = '0'
130        sys.argv[l] = head.replace('without-','with-')+'='+tail
131
132
133def chksynonyms():
134  #replace common configure options with ones that PETSc BuildSystem recognizes
135  for l in range(0,len(sys.argv)):
136    name = sys.argv[l]
137
138
139    if name.find('with-debug=') >= 0 or name.endswith('with-debug'):
140      if name.find('=') == -1:
141        sys.argv[l] = name.replace('with-debug','with-debugging')+'=1'
142      else:
143        head, tail = name.split('=', 1)
144        sys.argv[l] = head.replace('with-debug','with-debugging')+'='+tail
145
146    if name.find('with-shared=') >= 0 or name.endswith('with-shared'):
147      if name.find('=') == -1:
148        sys.argv[l] = name.replace('with-shared','with-shared-libraries')+'=1'
149      else:
150        head, tail = name.split('=', 1)
151        sys.argv[l] = head.replace('with-shared','with-shared-libraries')+'='+tail
152
153    if name.find('with-index-size=') >=0:
154      head,tail = name.split('=',1)
155      if int(tail)==32:
156        sys.argv[l] = '--with-64-bit-indices=0'
157      elif int(tail)==64:
158        sys.argv[l] = '--with-64-bit-indices=1'
159      else:
160        raise RuntimeError('--with-index-size= must be 32 or 64')
161
162    if name.find('with-precision=') >=0:
163      head,tail = name.split('=',1)
164      if tail.find('quad')>=0:
165        sys.argv[l]='--with-precision=__float128'
166
167
168def chkwinf90():
169  for arg in sys.argv:
170    if (arg.find('win32fe') >= 0 and (arg.find('f90') >=0 or arg.find('ifort') >=0)):
171      return 1
172  return 0
173
174def chkdosfiles():
175  # cygwin - but not a hg clone - so check one of files in bin dir
176  if "\r\n" in open(os.path.join('bin','petscmpiexec'),"rb").read():
177    print '==============================================================================='
178    print ' *** Scripts are in DOS mode. Was winzip used to extract petsc sources?    ****'
179    print ' *** Please restart with a fresh tarball and use "tar -xzf petsc.tar.gz"   ****'
180    print '==============================================================================='
181    sys.exit(3)
182  return
183
184def chkcygwinlink():
185  if os.path.exists('/usr/bin/cygcheck.exe') and os.path.exists('/usr/bin/link.exe') and chkwinf90():
186      if '--ignore-cygwin-link' in sys.argv: return 0
187      print '==============================================================================='
188      print ' *** Cygwin /usr/bin/link detected! Compiles with CVF/Intel f90 can break!  **'
189      print ' *** To workarround do: "mv /usr/bin/link.exe /usr/bin/link-cygwin.exe"     **'
190      print ' *** Or to ignore this check, use configure option: --ignore-cygwin-link    **'
191      print '==============================================================================='
192      sys.exit(3)
193  return 0
194
195def chkbrokencygwin():
196  if os.path.exists('/usr/bin/cygcheck.exe'):
197    buf = os.popen('/usr/bin/cygcheck.exe -c cygwin').read()
198    if buf.find('1.5.11-1') > -1:
199      print '==============================================================================='
200      print ' *** cygwin-1.5.11-1 detected. ./configure fails with this version ***'
201      print ' *** Please upgrade to cygwin-1.5.12-1 or newer version. This can  ***'
202      print ' *** be done by running cygwin-setup, selecting "next" all the way.***'
203      print '==============================================================================='
204      sys.exit(3)
205  return 0
206
207def chkusingwindowspython():
208  if sys.platform == 'win32':
209    print '==============================================================================='
210    print ' *** Windows python detected. Please rerun ./configure with cygwin-python. ***'
211    print '==============================================================================='
212    sys.exit(3)
213  return 0
214
215def chkcygwinpython():
216  if sys.platform == 'cygwin' :
217    import platform
218    import re
219    r=re.compile("([0-9]+).([0-9]+).([0-9]+)")
220    m=r.match(platform.release())
221    major=int(m.group(1))
222    minor=int(m.group(2))
223    subminor=int(m.group(3))
224    if ((major < 1) or (major == 1 and minor < 7) or (major == 1 and minor == 7 and subminor < 34)):
225      sys.argv.append('--useThreads=0')
226      extraLogs.append('''\
227===============================================================================
228** Cygwin version is older than 1.7.34. Python threads do not work correctly. ***
229** Disabling thread usage for this run of ./configure *******
230===============================================================================''')
231  return 0
232
233def chkrhl9():
234  if os.path.exists('/etc/redhat-release'):
235    try:
236      file = open('/etc/redhat-release','r')
237      buf = file.read()
238      file.close()
239    except:
240      # can't read file - assume dangerous RHL9
241      buf = 'Shrike'
242    if buf.find('Shrike') > -1:
243      sys.argv.append('--useThreads=0')
244      extraLogs.append('''\
245==============================================================================
246   *** RHL9 detected. Threads do not work correctly with this distribution ***
247   ****** Disabling thread usage for this run of ./configure *********
248===============================================================================''')
249  return 0
250
251def check_broken_configure_log_links():
252  '''Sometime symlinks can get broken if the original files are deleted. Delete such broken links'''
253  import os
254  for logfile in ['configure.log','configure.log.bkp']:
255    if os.path.islink(logfile) and not os.path.isfile(logfile): os.remove(logfile)
256  return
257
258def move_configure_log(framework):
259  '''Move configure.log to PETSC_ARCH/lib/petsc/conf - and update configure.log.bkp in both locations appropriately'''
260  global petsc_arch
261
262  if hasattr(framework,'arch'): petsc_arch = framework.arch
263  if hasattr(framework,'logName'): curr_file = framework.logName
264  else: curr_file = 'configure.log'
265
266  if petsc_arch:
267    import shutil
268    import os
269
270    # Just in case - confdir is not created
271    lib_dir = os.path.join(petsc_arch,'lib')
272    conf_dir = os.path.join(petsc_arch,'lib','petsc','conf')
273    if not os.path.isdir(petsc_arch): os.mkdir(petsc_arch)
274    if not os.path.isdir(lib_dir): os.mkdir(lib_dir)
275    if not os.path.isdir(conf_dir): os.mkdir(conf_dir)
276
277    curr_bkp  = curr_file + '.bkp'
278    new_file  = os.path.join(conf_dir,curr_file)
279    new_bkp   = new_file + '.bkp'
280
281    # Keep backup in $PETSC_ARCH/lib/petsc/conf location
282    if os.path.isfile(new_bkp): os.remove(new_bkp)
283    if os.path.isfile(new_file): os.rename(new_file,new_bkp)
284    if os.path.isfile(curr_file):
285      shutil.copyfile(curr_file,new_file)
286      os.remove(curr_file)
287    if os.path.isfile(new_file): os.symlink(new_file,curr_file)
288    # If the old bkp is using the same PETSC_ARCH/lib/petsc/conf - then update bkp link
289    if os.path.realpath(curr_bkp) == os.path.realpath(new_file):
290      if os.path.isfile(curr_bkp): os.remove(curr_bkp)
291      if os.path.isfile(new_bkp): os.symlink(new_bkp,curr_bkp)
292  return
293
294def print_final_timestamp(framework):
295  import time
296  framework.log.write(('='*80)+'\n')
297  framework.log.write('Finishing Configure Run at '+time.ctime(time.time())+'\n')
298  framework.log.write(('='*80)+'\n')
299  return
300
301def petsc_configure(configure_options):
302  try:
303    petscdir = os.environ['PETSC_DIR']
304    sys.path.append(os.path.join(petscdir,'bin'))
305    import petscnagupgrade
306    file     = os.path.join(petscdir,'.nagged')
307    if not petscnagupgrade.naggedtoday(file):
308      petscnagupgrade.currentversion(petscdir)
309  except:
310    pass
311  print '==============================================================================='
312  print '             Configuring PETSc to compile on your system                       '
313  print '==============================================================================='
314
315  try:
316    # Command line arguments take precedence (but don't destroy argv[0])
317    sys.argv = sys.argv[:1] + configure_options + sys.argv[1:]
318    check_for_option_mistakes(sys.argv)
319    check_for_option_changed(sys.argv)
320  except (TypeError, ValueError), e:
321    emsg = str(e)
322    if not emsg.endswith('\n'): emsg = emsg+'\n'
323    msg ='*******************************************************************************\n'\
324    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
325    +'-------------------------------------------------------------------------------\n'  \
326    +emsg+'*******************************************************************************\n'
327    sys.exit(msg)
328  # check PETSC_ARCH
329  check_petsc_arch(sys.argv)
330  check_broken_configure_log_links()
331
332  #rename '--enable-' to '--with-'
333  chkenable()
334  # support a few standard configure option types
335  chksynonyms()
336  # Check for broken cygwin
337  chkbrokencygwin()
338  # Disable threads on RHL9
339  chkrhl9()
340  # Make sure cygwin-python is used on windows
341  chkusingwindowspython()
342  # Threads don't work for cygwin & python...
343  chkcygwinpython()
344  chkcygwinlink()
345  chkdosfiles()
346
347  # Should be run from the toplevel
348  configDir = os.path.abspath('config')
349  bsDir     = os.path.join(configDir, 'BuildSystem')
350  if not os.path.isdir(configDir):
351    raise RuntimeError('Run configure from $PETSC_DIR, not '+os.path.abspath('.'))
352  sys.path.insert(0, bsDir)
353  sys.path.insert(0, configDir)
354  import config.base
355  import config.framework
356  import cPickle
357
358  framework = None
359  try:
360    framework = config.framework.Framework(['--configModules=PETSc.Configure','--optionsModule=config.compilerOptions']+sys.argv[1:], loadArgDB = 0)
361    framework.setup()
362    framework.logPrint('\n'.join(extraLogs))
363    framework.configure(out = sys.stdout)
364    framework.storeSubstitutions(framework.argDB)
365    framework.argDB['configureCache'] = cPickle.dumps(framework)
366    framework.printSummary()
367    framework.argDB.save(force = True)
368    framework.logClear()
369    print_final_timestamp(framework)
370    framework.closeLog()
371    try:
372      move_configure_log(framework)
373    except:
374      # perhaps print an error about unable to shuffle logs?
375      pass
376    return 0
377  except (RuntimeError, config.base.ConfigureSetupError), e:
378    emsg = str(e)
379    if not emsg.endswith('\n'): emsg = emsg+'\n'
380    msg ='*******************************************************************************\n'\
381    +'         UNABLE to CONFIGURE with GIVEN OPTIONS    (see configure.log for details):\n' \
382    +'-------------------------------------------------------------------------------\n'  \
383    +emsg+'*******************************************************************************\n'
384    se = ''
385  except (TypeError, ValueError), e:
386    emsg = str(e)
387    if not emsg.endswith('\n'): emsg = emsg+'\n'
388    msg ='*******************************************************************************\n'\
389    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
390    +'-------------------------------------------------------------------------------\n'  \
391    +emsg+'*******************************************************************************\n'
392    se = ''
393  except ImportError, e :
394    emsg = str(e)
395    if not emsg.endswith('\n'): emsg = emsg+'\n'
396    msg ='*******************************************************************************\n'\
397    +'                     UNABLE to FIND MODULE for ./configure \n' \
398    +'-------------------------------------------------------------------------------\n'  \
399    +emsg+'*******************************************************************************\n'
400    se = ''
401  except OSError, e :
402    emsg = str(e)
403    if not emsg.endswith('\n'): emsg = emsg+'\n'
404    msg ='*******************************************************************************\n'\
405    +'                    UNABLE to EXECUTE BINARIES for ./configure \n' \
406    +'-------------------------------------------------------------------------------\n'  \
407    +emsg+'*******************************************************************************\n'
408    se = ''
409  except SystemExit, e:
410    if e.code is None or e.code == 0:
411      return
412    msg ='*******************************************************************************\n'\
413    +'         CONFIGURATION FAILURE  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
414    +'*******************************************************************************\n'
415    se  = str(e)
416  except Exception, e:
417    msg ='*******************************************************************************\n'\
418    +'        CONFIGURATION CRASH  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
419    +'*******************************************************************************\n'
420    se  = str(e)
421
422  print msg
423  if not framework is None:
424    framework.logClear()
425    if hasattr(framework, 'log'):
426      try:
427        if hasattr(framework,'compilerDefines'):
428          framework.log.write('**** Configure header '+framework.compilerDefines+' ****\n')
429          framework.outputHeader(framework.log)
430        if hasattr(framework,'compilerFixes'):
431          framework.log.write('**** C specific Configure header '+framework.compilerFixes+' ****\n')
432          framework.outputCHeader(framework.log)
433      except Exception, e:
434        framework.log.write('Problem writing headers to log: '+str(e))
435      import traceback
436      try:
437        framework.log.write(msg+se)
438        traceback.print_tb(sys.exc_info()[2], file = framework.log)
439        print_final_timestamp(framework)
440        if hasattr(framework,'log'): framework.log.close()
441        move_configure_log(framework)
442      except:
443        pass
444      sys.exit(1)
445  else:
446    print se
447    import traceback
448    traceback.print_tb(sys.exc_info()[2])
449  if hasattr(framework,'log'): framework.log.close()
450
451if __name__ == '__main__':
452  petsc_configure([])
453
454