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