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