xref: /petsc/config/configure.py (revision 5a856986583887c326abe5dfd149e8184a29cd80)
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
9if 'LC_LOCAL' in os.environ and os.environ['LC_LOCAL'] != '' and os.environ['LC_LOCAL'] != 'en_US' and os.environ['LC_LOCAL']!= 'en_US.UTF-8': os.environ['LC_LOCAL'] = 'en_US.UTF-8'
10if 'LANG' in os.environ and os.environ['LANG'] != '' and os.environ['LANG'] != 'en_US' and os.environ['LANG'] != 'en_US.UTF-8': os.environ['LANG'] = 'en_US.UTF-8'
11
12if sys.version_info < (2,6):
13  print('************************************************************************')
14  print('*      Python version 2.6+ or 3.4+ is required to run ./configure      *')
15  print('*         Try: "python2.7 ./configure" or "python3 ./configure"        *')
16  print('************************************************************************')
17  sys.exit(4)
18
19def check_for_option_mistakes(opts):
20  for opt in opts[1:]:
21    name = opt.split('=')[0]
22    if name.find('_') >= 0:
23      exception = False
24      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']:
25        if name.find(exc) >= 0:
26          exception = True
27      if not exception:
28        raise ValueError('The option '+name+' should probably be '+name.replace('_', '-'));
29    if opt.find('=') >=0:
30      optval = opt.split('=')[1]
31      if optval == 'ifneeded':
32        raise ValueError('The option '+opt+' should probably be '+opt.replace('ifneeded', '1'));
33  return
34
35def check_for_unsupported_combinations(opts):
36  if '--with-precision=single' in opts and '--with-clanguage=cxx' in opts and '--with-scalar-type=complex' in opts:
37    sys.exit(ValueError('PETSc does not support single precision complex with C++ clanguage, run with --with-clanguage=c'))
38
39def check_for_option_changed(opts):
40# Document changes in command line options here.
41  optMap = [('with-64bit-indices','with-64-bit-indices'),
42            ('with-mpi-exec','with-mpiexec'),
43            ('c-blas-lapack','f2cblaslapack'),
44            ('cholmod','suitesparse'),
45            ('umfpack','suitesparse'),
46            ('f-blas-lapack','fblaslapack'),
47            ('with-cuda-arch',
48             'CUDAFLAGS=-arch'),
49            ('with-packages-dir','with-packages-download-dir'),
50            ('with-external-packages-dir','with-packages-build-dir'),
51            ('package-dirs','with-packages-search-path'),
52            ('download-petsc4py-python','with-python-exec'),
53            ('search-dirs','with-executables-search-path')]
54  for opt in opts[1:]:
55    optname = opt.split('=')[0].strip('-')
56    for oldname,newname in optMap:
57      if optname.find(oldname) >=0:
58        raise ValueError('The option '+opt+' should probably be '+opt.replace(oldname,newname))
59  return
60
61def check_petsc_arch(opts):
62  # If PETSC_ARCH not specified - use script name (if not configure.py)
63  global petsc_arch
64  found = 0
65  for name in opts:
66    if name.find('PETSC_ARCH=') >= 0:
67      petsc_arch=name.split('=')[1]
68      found = 1
69      break
70  # If not yet specified - use the filename of script
71  if not found:
72      filename = os.path.basename(sys.argv[0])
73      if not filename.startswith('configure') and not filename.startswith('reconfigure') and not filename.startswith('setup'):
74        petsc_arch=os.path.splitext(os.path.basename(sys.argv[0]))[0]
75        useName = 'PETSC_ARCH='+petsc_arch
76        opts.append(useName)
77  return 0
78
79def chkenable():
80  #Replace all 'enable-'/'disable-' with 'with-'=0/1/tail
81  #enable-fortran is a special case, the resulting --with-fortran is ambiguous.
82  #Would it mean --with-fc=
83  en_dash = u'\N{EN DASH}'
84  if sys.version_info < (3, 0):
85    en_dash = en_dash.encode('utf-8')
86  for l in range(0,len(sys.argv)):
87    name = sys.argv[l]
88
89    if name.find(en_dash)  >= 0:
90      sys.argv[l] = name.replace(en_dash,'-')
91    if name.find('enable-cxx') >= 0:
92      if name.find('=') == -1:
93        sys.argv[l] = name.replace('enable-cxx','with-clanguage=C++')
94      else:
95        head, tail = name.split('=', 1)
96        if tail=='0':
97          sys.argv[l] = head.replace('enable-cxx','with-clanguage=C')
98        else:
99          sys.argv[l] = head.replace('enable-cxx','with-clanguage=C++')
100      continue
101    if name.find('disable-cxx') >= 0:
102      if name.find('=') == -1:
103        sys.argv[l] = name.replace('disable-cxx','with-clanguage=C')
104      else:
105        head, tail = name.split('=', 1)
106        if tail == '0':
107          sys.argv[l] = head.replace('disable-cxx','with-clanguage=C++')
108        else:
109          sys.argv[l] = head.replace('disable-cxx','with-clanguage=C')
110      continue
111
112
113    if name.find('enable-') >= 0:
114      if name.find('=') == -1:
115        sys.argv[l] = name.replace('enable-','with-')+'=1'
116      else:
117        head, tail = name.split('=', 1)
118        sys.argv[l] = head.replace('enable-','with-')+'='+tail
119    if name.find('disable-') >= 0:
120      if name.find('=') == -1:
121        sys.argv[l] = name.replace('disable-','with-')+'=0'
122      else:
123        head, tail = name.split('=', 1)
124        if tail == '1': tail = '0'
125        sys.argv[l] = head.replace('disable-','with-')+'='+tail
126    if name.find('without-') >= 0:
127      if name.find('=') == -1:
128        sys.argv[l] = name.replace('without-','with-')+'=0'
129      else:
130        head, tail = name.split('=', 1)
131        if tail == '1': tail = '0'
132        sys.argv[l] = head.replace('without-','with-')+'='+tail
133
134def chksynonyms():
135  #replace common configure options with ones that PETSc BuildSystem recognizes
136  simplereplacements = {'F77' : 'FC', 'F90' : 'FC'}
137  for l in range(0,len(sys.argv)):
138    name = sys.argv[l]
139
140    if name.find('with-blas-lapack') >= 0:
141      sys.argv[l] = name.replace('with-blas-lapack','with-blaslapack')
142
143    if name.find('with-debug=') >= 0 or name.endswith('with-debug'):
144      if name.find('=') == -1:
145        sys.argv[l] = name.replace('with-debug','with-debugging')+'=1'
146      else:
147        head, tail = name.split('=', 1)
148        sys.argv[l] = head.replace('with-debug','with-debugging')+'='+tail
149
150    if name.find('with-shared=') >= 0 or name.endswith('with-shared'):
151      if name.find('=') == -1:
152        sys.argv[l] = name.replace('with-shared','with-shared-libraries')+'=1'
153      else:
154        head, tail = name.split('=', 1)
155        sys.argv[l] = head.replace('with-shared','with-shared-libraries')+'='+tail
156
157    if name.find('with-index-size=') >=0:
158      head,tail = name.split('=',1)
159      if int(tail)==32:
160        sys.argv[l] = '--with-64-bit-indices=0'
161      elif int(tail)==64:
162        sys.argv[l] = '--with-64-bit-indices=1'
163      else:
164        raise RuntimeError('--with-index-size= must be 32 or 64')
165
166    if name.find('with-precision=') >=0:
167      head,tail = name.split('=',1)
168      if tail.find('quad')>=0:
169        sys.argv[l]='--with-precision=__float128'
170
171    for i,j in simplereplacements.items():
172      if name.find(i+'=') >= 0:
173        sys.argv[l] = name.replace(i+'=',j+'=')
174      elif name.find('with-'+i.lower()+'=') >= 0:
175        sys.argv[l] = name.replace(i.lower()+'=',j.lower()+'=')
176
177def chkwinf90():
178  for arg in sys.argv:
179    if (arg.find('win32fe') >= 0 and (arg.find('f90') >=0 or arg.find('ifort') >=0)):
180      return 1
181  return 0
182
183def chkdosfiles():
184  # cygwin - but not a hg clone - so check one of files in bin dir
185  if b"\r\n" in open(os.path.join('lib','petsc','bin','petscmpiexec'),"rb").read():
186    print('===============================================================================')
187    print(' *** Scripts are in DOS mode. Was winzip used to extract petsc sources?    ****')
188    print(' *** Please restart with a fresh tarball and use "tar -xzf petsc.tar.gz"   ****')
189    print('===============================================================================')
190    sys.exit(3)
191  return
192
193def chkcygwinlink():
194  if os.path.exists('/usr/bin/cygcheck.exe') and os.path.exists('/usr/bin/link.exe') and chkwinf90():
195      if '--ignore-cygwin-link' in sys.argv: return 0
196      print('===============================================================================')
197      print(' *** Cygwin /usr/bin/link detected! Compiles with CVF/Intel f90 can break!  **')
198      print(' *** To workarround do: "mv /usr/bin/link.exe /usr/bin/link-cygwin.exe"     **')
199      print(' *** Or to ignore this check, use configure option: --ignore-cygwin-link    **')
200      print('===============================================================================')
201      sys.exit(3)
202  return 0
203
204def chkbrokencygwin():
205  if os.path.exists('/usr/bin/cygcheck.exe'):
206    buf = os.popen('/usr/bin/cygcheck.exe -c cygwin').read()
207    if buf.find('1.5.11-1') > -1:
208      print('===============================================================================')
209      print(' *** cygwin-1.5.11-1 detected. ./configure fails with this version ***')
210      print(' *** Please upgrade to cygwin-1.5.12-1 or newer version. This can  ***')
211      print(' *** be done by running cygwin-setup, selecting "next" all the way.***')
212      print('===============================================================================')
213      sys.exit(3)
214  return 0
215
216def chkusingwindowspython():
217  if sys.platform == 'win32':
218    print('===============================================================================')
219    print(' *** Windows python detected. Please rerun ./configure with cygwin-python. ***')
220    print('===============================================================================')
221    sys.exit(3)
222  return 0
223
224def chkcygwinpython():
225  if sys.platform == 'cygwin' :
226    import platform
227    import re
228    r=re.compile("([0-9]+).([0-9]+).([0-9]+)")
229    m=r.match(platform.release())
230    major=int(m.group(1))
231    minor=int(m.group(2))
232    subminor=int(m.group(3))
233    if ((major < 1) or (major == 1 and minor < 7) or (major == 1 and minor == 7 and subminor < 34)):
234      sys.argv.append('--useThreads=0')
235      extraLogs.append('''\
236===============================================================================
237** Cygwin version is older than 1.7.34. Python threads do not work correctly. ***
238** Disabling thread usage for this run of ./configure *******
239===============================================================================''')
240  return 0
241
242def chkrhl9():
243  if os.path.exists('/etc/redhat-release'):
244    try:
245      file = open('/etc/redhat-release','r')
246      buf = file.read()
247      file.close()
248    except:
249      # can't read file - assume dangerous RHL9
250      buf = 'Shrike'
251    if buf.find('Shrike') > -1:
252      sys.argv.append('--useThreads=0')
253      extraLogs.append('''\
254==============================================================================
255   *** RHL9 detected. Threads do not work correctly with this distribution ***
256   ****** Disabling thread usage for this run of ./configure *********
257===============================================================================''')
258  return 0
259
260def check_broken_configure_log_links():
261  '''Sometime symlinks can get broken if the original files are deleted. Delete such broken links'''
262  import os
263  for logfile in ['configure.log','configure.log.bkp']:
264    if os.path.islink(logfile) and not os.path.isfile(logfile): os.remove(logfile)
265  return
266
267def move_configure_log(framework):
268  '''Move configure.log to PETSC_ARCH/lib/petsc/conf - and update configure.log.bkp in both locations appropriately'''
269  global petsc_arch
270
271  if hasattr(framework,'arch'): petsc_arch = framework.arch
272  if hasattr(framework,'logName'): curr_file = framework.logName
273  else: curr_file = 'configure.log'
274
275  if petsc_arch:
276    import shutil
277    import os
278
279    # Just in case - confdir is not created
280    lib_dir = os.path.join(petsc_arch,'lib')
281    conf_dir = os.path.join(petsc_arch,'lib','petsc','conf')
282    if not os.path.isdir(petsc_arch): os.mkdir(petsc_arch)
283    if not os.path.isdir(lib_dir): os.mkdir(lib_dir)
284    if not os.path.isdir(conf_dir): os.mkdir(conf_dir)
285
286    curr_bkp  = curr_file + '.bkp'
287    new_file  = os.path.join(conf_dir,curr_file)
288    new_bkp   = new_file + '.bkp'
289
290    # Keep backup in $PETSC_ARCH/lib/petsc/conf location
291    if os.path.isfile(new_bkp): os.remove(new_bkp)
292    if os.path.isfile(new_file): os.rename(new_file,new_bkp)
293    if os.path.isfile(curr_file):
294      shutil.copyfile(curr_file,new_file)
295      os.remove(curr_file)
296    if os.path.isfile(new_file): os.symlink(new_file,curr_file)
297    # If the old bkp is using the same PETSC_ARCH/lib/petsc/conf - then update bkp link
298    if os.path.realpath(curr_bkp) == os.path.realpath(new_file):
299      if os.path.isfile(curr_bkp): os.remove(curr_bkp)
300      if os.path.isfile(new_bkp): os.symlink(new_bkp,curr_bkp)
301  return
302
303def print_final_timestamp(framework):
304  import time
305  framework.log.write(('='*80)+'\n')
306  framework.log.write('Finishing configure run at '+time.strftime('%a, %d %b %Y %H:%M:%S %z')+'\n')
307  framework.log.write(('='*80)+'\n')
308  return
309
310def petsc_configure(configure_options):
311  if 'PETSC_DIR' in os.environ:
312    petscdir = os.environ['PETSC_DIR']
313    if petscdir.find(' ') > -1:
314      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')
315    try:
316      sys.path.append(os.path.join(petscdir,'lib','petsc','bin'))
317      import petscnagupgrade
318      file     = os.path.join(petscdir,'.nagged')
319      if not petscnagupgrade.naggedtoday(file):
320        petscnagupgrade.currentversion(petscdir)
321    except:
322      pass
323  print('===============================================================================')
324  print('             Configuring PETSc to compile on your system                       ')
325  print('===============================================================================')
326
327  try:
328    # Command line arguments take precedence (but don't destroy argv[0])
329    sys.argv = sys.argv[:1] + configure_options + sys.argv[1:]
330    check_for_option_mistakes(sys.argv)
331    check_for_option_changed(sys.argv)
332  except (TypeError, ValueError) as e:
333    emsg = str(e)
334    if not emsg.endswith('\n'): emsg = emsg+'\n'
335    msg ='*******************************************************************************\n'\
336    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
337    +'-------------------------------------------------------------------------------\n'  \
338    +emsg+'*******************************************************************************\n'
339    sys.exit(msg)
340  # check PETSC_ARCH
341  check_for_unsupported_combinations(sys.argv)
342  check_petsc_arch(sys.argv)
343  check_broken_configure_log_links()
344
345  #rename '--enable-' to '--with-'
346  chkenable()
347  # support a few standard configure option types
348  chksynonyms()
349  # Check for broken cygwin
350  chkbrokencygwin()
351  # Disable threads on RHL9
352  chkrhl9()
353  # Make sure cygwin-python is used on windows
354  chkusingwindowspython()
355  # Threads don't work for cygwin & python...
356  chkcygwinpython()
357  chkcygwinlink()
358  chkdosfiles()
359
360  # Should be run from the toplevel
361  configDir = os.path.abspath('config')
362  bsDir     = os.path.join(configDir, 'BuildSystem')
363  if not os.path.isdir(configDir):
364    raise RuntimeError('Run configure from $PETSC_DIR, not '+os.path.abspath('.'))
365  sys.path.insert(0, bsDir)
366  sys.path.insert(0, configDir)
367  import config.base
368  import config.framework
369  import pickle
370
371  framework = None
372  try:
373    framework = config.framework.Framework(['--configModules=PETSc.Configure','--optionsModule=config.compilerOptions']+sys.argv[1:], loadArgDB = 0)
374    framework.setup()
375    framework.logPrint('\n'.join(extraLogs))
376    framework.configure(out = sys.stdout)
377    framework.storeSubstitutions(framework.argDB)
378    framework.argDB['configureCache'] = pickle.dumps(framework)
379    framework.printSummary()
380    framework.argDB.save(force = True)
381    framework.logClear()
382    print_final_timestamp(framework)
383    framework.closeLog()
384    try:
385      move_configure_log(framework)
386    except:
387      # perhaps print an error about unable to shuffle logs?
388      pass
389    return 0
390  except (RuntimeError, config.base.ConfigureSetupError) as e:
391    emsg = str(e)
392    if not emsg.endswith('\n'): emsg = emsg+'\n'
393    msg ='*******************************************************************************\n'\
394    +'         UNABLE to CONFIGURE with GIVEN OPTIONS    (see configure.log for details):\n' \
395    +'-------------------------------------------------------------------------------\n'  \
396    +emsg+'*******************************************************************************\n'
397    se = ''
398  except (TypeError, ValueError) as e:
399    emsg = str(e)
400    if not emsg.endswith('\n'): emsg = emsg+'\n'
401    msg ='*******************************************************************************\n'\
402    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
403    +'-------------------------------------------------------------------------------\n'  \
404    +emsg+'*******************************************************************************\n'
405    se = ''
406  except ImportError as e :
407    emsg = str(e)
408    if not emsg.endswith('\n'): emsg = emsg+'\n'
409    msg ='*******************************************************************************\n'\
410    +'                     UNABLE to FIND MODULE for ./configure \n' \
411    +'-------------------------------------------------------------------------------\n'  \
412    +emsg+'*******************************************************************************\n'
413    se = ''
414  except OSError as e :
415    emsg = str(e)
416    if not emsg.endswith('\n'): emsg = emsg+'\n'
417    msg ='*******************************************************************************\n'\
418    +'                    UNABLE to EXECUTE BINARIES for ./configure \n' \
419    +'-------------------------------------------------------------------------------\n'  \
420    +emsg+'*******************************************************************************\n'
421    se = ''
422  except SystemExit as e:
423    if e.code is None or e.code == 0:
424      return
425    if e.code is 10:
426      sys.exit(10)
427    msg ='*******************************************************************************\n'\
428    +'         CONFIGURATION FAILURE  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
429    +'*******************************************************************************\n'
430    se  = str(e)
431  except Exception as e:
432    msg ='*******************************************************************************\n'\
433    +'        CONFIGURATION CRASH  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
434    +'*******************************************************************************\n'
435    se  = str(e)
436
437  print(msg)
438  if not framework is None:
439    framework.logClear()
440    if hasattr(framework, 'log'):
441      try:
442        if hasattr(framework,'compilerDefines'):
443          framework.log.write('**** Configure header '+framework.compilerDefines+' ****\n')
444          framework.outputHeader(framework.log)
445        if hasattr(framework,'compilerFixes'):
446          framework.log.write('**** C specific Configure header '+framework.compilerFixes+' ****\n')
447          framework.outputCHeader(framework.log)
448      except Exception as e:
449        framework.log.write('Problem writing headers to log: '+str(e))
450      import traceback
451      try:
452        framework.log.write(msg+se)
453        traceback.print_tb(sys.exc_info()[2], file = framework.log)
454        print_final_timestamp(framework)
455        if hasattr(framework,'log'): framework.log.close()
456        move_configure_log(framework)
457      except:
458        pass
459      sys.exit(1)
460  else:
461    print(se)
462    import traceback
463    traceback.print_tb(sys.exc_info()[2])
464  if hasattr(framework,'log'): framework.log.close()
465
466if __name__ == '__main__':
467  petsc_configure([])
468
469