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