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