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