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