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