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