xref: /petsc/config/configure.py (revision 6ccf5d5763ee3ff4fd455dfd2a4a28ab2072f039)
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
131def argsAddDownload(value,deps = [],options = []):
132  # Adds --download-value to args if the command line DOES NOT already has --with-value or --download-value in it
133  # this is to prevent introducing conflicting arguments to ones that already exist
134  for opt in sys.argv[1:]:
135    optname = opt.split('=')[0].strip('-')
136    if optname in ['download-'+value,'with-'+value,'with-'+value+'-dir','with-'+value+'-include','with-'+value+'-lib']: return
137  sys.argv.append('--download-'+value)
138  for i in deps:
139    argsAddDownload(i)
140  for i in options:
141    sys.argv.append(i)
142
143def chksynonyms():
144  #replace common configure options with ones that PETSc BuildSystem recognizes
145  downloadxsdk = 0
146  downloadideas = 0
147  for l in range(0,len(sys.argv)):
148    name = sys.argv[l]
149
150    if name.find('download-xsdk=') >= 0 or name.endswith('download-xsdk'):
151      downloadxsdk = 1
152
153    if name.find('download-ideas=') >= 0 or name.endswith('download-ideas'):
154      downloadideas = 1
155
156    if name.find('with-debug=') >= 0 or name.endswith('with-debug'):
157      if name.find('=') == -1:
158        sys.argv[l] = name.replace('with-debug','with-debugging')+'=1'
159      else:
160        head, tail = name.split('=', 1)
161        sys.argv[l] = head.replace('with-debug','with-debugging')+'='+tail
162
163    if name.find('with-shared=') >= 0 or name.endswith('with-shared'):
164      if name.find('=') == -1:
165        sys.argv[l] = name.replace('with-shared','with-shared-libraries')+'=1'
166      else:
167        head, tail = name.split('=', 1)
168        sys.argv[l] = head.replace('with-shared','with-shared-libraries')+'='+tail
169
170    if name.find('with-index-size=') >=0:
171      head,tail = name.split('=',1)
172      if int(tail)==32:
173        sys.argv[l] = '--with-64-bit-indices=0'
174      elif int(tail)==64:
175        sys.argv[l] = '--with-64-bit-indices=1'
176      else:
177        raise RuntimeError('--with-index-size= must be 32 or 64')
178
179    if name.find('with-precision=') >=0:
180      head,tail = name.split('=',1)
181      if tail.find('quad')>=0:
182        sys.argv[l]='--with-precision=__float128'
183
184  if downloadideas:
185    downloadxsdk = 1
186    argsAddDownload('pflotran')
187    argsAddDownload('alquimia')
188    # mstk currently cannot build a shared library
189    argsAddDownload('mstk',[],['--download-mstk-shared=0'])
190    argsAddDownload('ascem-io')
191    argsAddDownload('unittestcpp')
192
193  if downloadxsdk:
194    # Common external libraries
195    argsAddDownload('hdf5')
196    argsAddDownload('netcdf')
197    argsAddDownload('metis')
198
199    argsAddDownload('superlu_dist',['parmetis'])
200
201    argsAddDownload('hypre')
202
203    argsAddDownload('trilinos',['boost','xsdktrilinos'],['--with-cxx-dialect=C++11'])
204
205
206def chkwinf90():
207  for arg in sys.argv:
208    if (arg.find('win32fe') >= 0 and (arg.find('f90') >=0 or arg.find('ifort') >=0)):
209      return 1
210  return 0
211
212def chkdosfiles():
213  # cygwin - but not a hg clone - so check one of files in bin dir
214  if "\r\n" in open(os.path.join('bin','petscmpiexec'),"rb").read():
215    print '==============================================================================='
216    print ' *** Scripts are in DOS mode. Was winzip used to extract petsc sources?    ****'
217    print ' *** Please restart with a fresh tarball and use "tar -xzf petsc.tar.gz"   ****'
218    print '==============================================================================='
219    sys.exit(3)
220  return
221
222def chkcygwinlink():
223  if os.path.exists('/usr/bin/cygcheck.exe') and os.path.exists('/usr/bin/link.exe') and chkwinf90():
224      if '--ignore-cygwin-link' in sys.argv: return 0
225      print '==============================================================================='
226      print ' *** Cygwin /usr/bin/link detected! Compiles with CVF/Intel f90 can break!  **'
227      print ' *** To workarround do: "mv /usr/bin/link.exe /usr/bin/link-cygwin.exe"     **'
228      print ' *** Or to ignore this check, use configure option: --ignore-cygwin-link    **'
229      print '==============================================================================='
230      sys.exit(3)
231  return 0
232
233def chkbrokencygwin():
234  if os.path.exists('/usr/bin/cygcheck.exe'):
235    buf = os.popen('/usr/bin/cygcheck.exe -c cygwin').read()
236    if buf.find('1.5.11-1') > -1:
237      print '==============================================================================='
238      print ' *** cygwin-1.5.11-1 detected. ./configure fails with this version ***'
239      print ' *** Please upgrade to cygwin-1.5.12-1 or newer version. This can  ***'
240      print ' *** be done by running cygwin-setup, selecting "next" all the way.***'
241      print '==============================================================================='
242      sys.exit(3)
243  return 0
244
245def chkusingwindowspython():
246  if sys.platform == 'win32':
247    print '==============================================================================='
248    print ' *** Windows python detected. Please rerun ./configure with cygwin-python. ***'
249    print '==============================================================================='
250    sys.exit(3)
251  return 0
252
253def chkcygwinpython():
254  if sys.platform == 'cygwin' :
255    import platform
256    import re
257    r=re.compile("([0-9]+).([0-9]+).([0-9]+)")
258    m=r.match(platform.release())
259    major=int(m.group(1))
260    minor=int(m.group(2))
261    subminor=int(m.group(3))
262    if ((major < 1) or (major == 1 and minor < 7) or (major == 1 and minor == 7 and subminor < 34)):
263      sys.argv.append('--useThreads=0')
264      extraLogs.append('''\
265===============================================================================
266** Cygwin version is older than 1.7.34. Python threads do not work correctly. ***
267** Disabling thread usage for this run of ./configure *******
268===============================================================================''')
269  return 0
270
271def chkrhl9():
272  if os.path.exists('/etc/redhat-release'):
273    try:
274      file = open('/etc/redhat-release','r')
275      buf = file.read()
276      file.close()
277    except:
278      # can't read file - assume dangerous RHL9
279      buf = 'Shrike'
280    if buf.find('Shrike') > -1:
281      sys.argv.append('--useThreads=0')
282      extraLogs.append('''\
283==============================================================================
284   *** RHL9 detected. Threads do not work correctly with this distribution ***
285   ****** Disabling thread usage for this run of ./configure *********
286===============================================================================''')
287  return 0
288
289def check_broken_configure_log_links():
290  '''Sometime symlinks can get broken if the original files are deleted. Delete such broken links'''
291  import os
292  for logfile in ['configure.log','configure.log.bkp']:
293    if os.path.islink(logfile) and not os.path.isfile(logfile): os.remove(logfile)
294  return
295
296def move_configure_log(framework):
297  '''Move configure.log to PETSC_ARCH/lib/petsc/conf - and update configure.log.bkp in both locations appropriately'''
298  global petsc_arch
299
300  if hasattr(framework,'arch'): petsc_arch = framework.arch
301  if hasattr(framework,'logName'): curr_file = framework.logName
302  else: curr_file = 'configure.log'
303
304  if petsc_arch:
305    import shutil
306    import os
307
308    # Just in case - confdir is not created
309    lib_dir = os.path.join(petsc_arch,'lib')
310    conf_dir = os.path.join(petsc_arch,'lib','petsc','conf')
311    if not os.path.isdir(petsc_arch): os.mkdir(petsc_arch)
312    if not os.path.isdir(lib_dir): os.mkdir(lib_dir)
313    if not os.path.isdir(conf_dir): os.mkdir(conf_dir)
314
315    curr_bkp  = curr_file + '.bkp'
316    new_file  = os.path.join(conf_dir,curr_file)
317    new_bkp   = new_file + '.bkp'
318
319    # Keep backup in $PETSC_ARCH/lib/petsc/conf location
320    if os.path.isfile(new_bkp): os.remove(new_bkp)
321    if os.path.isfile(new_file): os.rename(new_file,new_bkp)
322    if os.path.isfile(curr_file):
323      shutil.copyfile(curr_file,new_file)
324      os.remove(curr_file)
325    if os.path.isfile(new_file): os.symlink(new_file,curr_file)
326    # If the old bkp is using the same PETSC_ARCH/lib/petsc/conf - then update bkp link
327    if os.path.realpath(curr_bkp) == os.path.realpath(new_file):
328      if os.path.isfile(curr_bkp): os.remove(curr_bkp)
329      if os.path.isfile(new_bkp): os.symlink(new_bkp,curr_bkp)
330  return
331
332def print_final_timestamp(framework):
333  import time
334  framework.log.write(('='*80)+'\n')
335  framework.log.write('Finishing Configure Run at '+time.ctime(time.time())+'\n')
336  framework.log.write(('='*80)+'\n')
337  return
338
339def petsc_configure(configure_options):
340  if 'PETSC_DIR' in os.environ:
341    petscdir = os.environ['PETSC_DIR']
342    if petscdir.find(' ') > -1:
343      raise RuntimeError('Your PETSC_DIR '+petscdir+' has spaces in it; this is not allowed.\n Change the directory with PETSc to not have spaces in it')
344    try:
345      sys.path.append(os.path.join(petscdir,'bin'))
346      import petscnagupgrade
347      file     = os.path.join(petscdir,'.nagged')
348      if not petscnagupgrade.naggedtoday(file):
349        petscnagupgrade.currentversion(petscdir)
350    except:
351      pass
352  print '==============================================================================='
353  print '             Configuring PETSc to compile on your system                       '
354  print '==============================================================================='
355
356  try:
357    # Command line arguments take precedence (but don't destroy argv[0])
358    sys.argv = sys.argv[:1] + configure_options + sys.argv[1:]
359    check_for_option_mistakes(sys.argv)
360    check_for_option_changed(sys.argv)
361  except (TypeError, ValueError), e:
362    emsg = str(e)
363    if not emsg.endswith('\n'): emsg = emsg+'\n'
364    msg ='*******************************************************************************\n'\
365    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
366    +'-------------------------------------------------------------------------------\n'  \
367    +emsg+'*******************************************************************************\n'
368    sys.exit(msg)
369  # check PETSC_ARCH
370  check_for_unsupported_combinations(sys.argv)
371  check_petsc_arch(sys.argv)
372  check_broken_configure_log_links()
373
374  #rename '--enable-' to '--with-'
375  chkenable()
376  # support a few standard configure option types
377  chksynonyms()
378  # Check for broken cygwin
379  chkbrokencygwin()
380  # Disable threads on RHL9
381  chkrhl9()
382  # Make sure cygwin-python is used on windows
383  chkusingwindowspython()
384  # Threads don't work for cygwin & python...
385  chkcygwinpython()
386  chkcygwinlink()
387  chkdosfiles()
388
389  # Should be run from the toplevel
390  configDir = os.path.abspath('config')
391  bsDir     = os.path.join(configDir, 'BuildSystem')
392  if not os.path.isdir(configDir):
393    raise RuntimeError('Run configure from $PETSC_DIR, not '+os.path.abspath('.'))
394  sys.path.insert(0, bsDir)
395  sys.path.insert(0, configDir)
396  import config.base
397  import config.framework
398  import cPickle
399
400  framework = None
401  try:
402    framework = config.framework.Framework(['--configModules=PETSc.Configure','--optionsModule=config.compilerOptions']+sys.argv[1:], loadArgDB = 0)
403    framework.setup()
404    framework.logPrint('\n'.join(extraLogs))
405    framework.configure(out = sys.stdout)
406    framework.storeSubstitutions(framework.argDB)
407    framework.argDB['configureCache'] = cPickle.dumps(framework)
408    framework.printSummary()
409    framework.argDB.save(force = True)
410    framework.logClear()
411    print_final_timestamp(framework)
412    framework.closeLog()
413    try:
414      move_configure_log(framework)
415    except:
416      # perhaps print an error about unable to shuffle logs?
417      pass
418    return 0
419  except (RuntimeError, config.base.ConfigureSetupError), e:
420    emsg = str(e)
421    if not emsg.endswith('\n'): emsg = emsg+'\n'
422    msg ='*******************************************************************************\n'\
423    +'         UNABLE to CONFIGURE with GIVEN OPTIONS    (see configure.log for details):\n' \
424    +'-------------------------------------------------------------------------------\n'  \
425    +emsg+'*******************************************************************************\n'
426    se = ''
427  except (TypeError, ValueError), e:
428    emsg = str(e)
429    if not emsg.endswith('\n'): emsg = emsg+'\n'
430    msg ='*******************************************************************************\n'\
431    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
432    +'-------------------------------------------------------------------------------\n'  \
433    +emsg+'*******************************************************************************\n'
434    se = ''
435  except ImportError, e :
436    emsg = str(e)
437    if not emsg.endswith('\n'): emsg = emsg+'\n'
438    msg ='*******************************************************************************\n'\
439    +'                     UNABLE to FIND MODULE for ./configure \n' \
440    +'-------------------------------------------------------------------------------\n'  \
441    +emsg+'*******************************************************************************\n'
442    se = ''
443  except OSError, e :
444    emsg = str(e)
445    if not emsg.endswith('\n'): emsg = emsg+'\n'
446    msg ='*******************************************************************************\n'\
447    +'                    UNABLE to EXECUTE BINARIES for ./configure \n' \
448    +'-------------------------------------------------------------------------------\n'  \
449    +emsg+'*******************************************************************************\n'
450    se = ''
451  except SystemExit, e:
452    if e.code is None or e.code == 0:
453      return
454    if e.code is 10:
455      sys.exit(10)
456    msg ='*******************************************************************************\n'\
457    +'         CONFIGURATION FAILURE  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
458    +'*******************************************************************************\n'
459    se  = str(e)
460  except Exception, e:
461    msg ='*******************************************************************************\n'\
462    +'        CONFIGURATION CRASH  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
463    +'*******************************************************************************\n'
464    se  = str(e)
465
466  print msg
467  if not framework is None:
468    framework.logClear()
469    if hasattr(framework, 'log'):
470      try:
471        if hasattr(framework,'compilerDefines'):
472          framework.log.write('**** Configure header '+framework.compilerDefines+' ****\n')
473          framework.outputHeader(framework.log)
474        if hasattr(framework,'compilerFixes'):
475          framework.log.write('**** C specific Configure header '+framework.compilerFixes+' ****\n')
476          framework.outputCHeader(framework.log)
477      except Exception, e:
478        framework.log.write('Problem writing headers to log: '+str(e))
479      import traceback
480      try:
481        framework.log.write(msg+se)
482        traceback.print_tb(sys.exc_info()[2], file = framework.log)
483        print_final_timestamp(framework)
484        if hasattr(framework,'log'): framework.log.close()
485        move_configure_log(framework)
486      except:
487        pass
488      sys.exit(1)
489  else:
490    print se
491    import traceback
492    traceback.print_tb(sys.exc_info()[2])
493  if hasattr(framework,'log'): framework.log.close()
494
495if __name__ == '__main__':
496  petsc_configure([])
497
498