xref: /petsc/config/configure.py (revision cc310fdddfd1255ff354b307e63afef1e66c265d)
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 = [('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 os.path.exists('/usr/bin/cygcheck.exe') and sys.platform == 'cygwin' :
183    sys.argv.append('--useThreads=0')
184    extraLogs.append('''\
185===============================================================================
186** Cygwin-python detected. Threads do not work correctly. ***
187** Disabling thread usage for this run of ./configure *******
188===============================================================================''')
189  return 0
190
191def chkrhl9():
192  if os.path.exists('/etc/redhat-release'):
193    try:
194      file = open('/etc/redhat-release','r')
195      buf = file.read()
196      file.close()
197    except:
198      # can't read file - assume dangerous RHL9
199      buf = 'Shrike'
200    if buf.find('Shrike') > -1:
201      sys.argv.append('--useThreads=0')
202      extraLogs.append('''\
203==============================================================================
204   *** RHL9 detected. Threads do not work correctly with this distribution ***
205   ****** Disabling thread usage for this run of ./configure *********
206===============================================================================''')
207  return 0
208
209def check_broken_configure_log_links():
210  '''Sometime symlinks can get broken if the original files are deleted. Delete such broken links'''
211  import os
212  for logfile in ['configure.log','configure.log.bkp']:
213    if os.path.islink(logfile) and not os.path.isfile(logfile): os.remove(logfile)
214  return
215
216def move_configure_log(framework):
217  '''Move configure.log to PETSC_ARCH/lib/petsc-conf - and update configure.log.bkp in both locations appropriately'''
218  global petsc_arch
219
220  if hasattr(framework,'arch'): petsc_arch = framework.arch
221  if hasattr(framework,'logName'): curr_file = framework.logName
222  else: curr_file = 'configure.log'
223
224  if petsc_arch:
225    import shutil
226    import os
227
228    # Just in case - confdir is not created
229    lib_dir = os.path.join(petsc_arch,'lib')
230    conf_dir = os.path.join(petsc_arch,'lib','petsc-conf')
231    if not os.path.isdir(petsc_arch): os.mkdir(petsc_arch)
232    if not os.path.isdir(lib_dir): os.mkdir(lib_dir)
233    if not os.path.isdir(conf_dir): os.mkdir(conf_dir)
234
235    curr_bkp  = curr_file + '.bkp'
236    new_file  = os.path.join(conf_dir,curr_file)
237    new_bkp   = new_file + '.bkp'
238
239    # Keep backup in $PETSC_ARCH/lib/petsc-conf location
240    if os.path.isfile(new_bkp): os.remove(new_bkp)
241    if os.path.isfile(new_file): os.rename(new_file,new_bkp)
242    if os.path.isfile(curr_file):
243      shutil.copyfile(curr_file,new_file)
244      os.remove(curr_file)
245    if os.path.isfile(new_file): os.symlink(new_file,curr_file)
246    # If the old bkp is using the same PETSC_ARCH/lib/petsc-conf - then update bkp link
247    if os.path.realpath(curr_bkp) == os.path.realpath(new_file):
248      if os.path.isfile(curr_bkp): os.remove(curr_bkp)
249      if os.path.isfile(new_bkp): os.symlink(new_bkp,curr_bkp)
250  return
251
252def print_final_timestamp(framework):
253  import time
254  framework.log.write(('='*80)+'\n')
255  framework.log.write('Finishing Configure Run at '+time.ctime(time.time())+'\n')
256  framework.log.write(('='*80)+'\n')
257  return
258
259def petsc_configure(configure_options):
260  try:
261    petscdir = os.environ['PETSC_DIR']
262    sys.path.append(os.path.join(petscdir,'bin','petsc-pythonscripts'))
263    import petscnagupgrade
264    file     = os.path.join(petscdir,'.nagged')
265    if not petscnagupgrade.naggedtoday(file):
266      petscnagupgrade.currentversion(petscdir)
267  except:
268    pass
269  print '==============================================================================='
270  print '             Configuring PETSc to compile on your system                       '
271  print '==============================================================================='
272
273  try:
274    # Command line arguments take precedence (but don't destroy argv[0])
275    sys.argv = sys.argv[:1] + configure_options + sys.argv[1:]
276    check_for_option_mistakes(sys.argv)
277    check_for_option_changed(sys.argv)
278  except (TypeError, ValueError), e:
279    emsg = str(e)
280    if not emsg.endswith('\n'): emsg = emsg+'\n'
281    msg ='*******************************************************************************\n'\
282    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
283    +'-------------------------------------------------------------------------------\n'  \
284    +emsg+'*******************************************************************************\n'
285    sys.exit(msg)
286  # check PETSC_ARCH
287  check_petsc_arch(sys.argv)
288  check_broken_configure_log_links()
289
290  #rename '--enable-' to '--with-'
291  chkenable()
292  # support a few standard configure option types
293  chksynonyms()
294  # Check for broken cygwin
295  chkbrokencygwin()
296  # Disable threads on RHL9
297  chkrhl9()
298  # Make sure cygwin-python is used on windows
299  chkusingwindowspython()
300  # Threads don't work for cygwin & python...
301  chkcygwinpython()
302  chkcygwinlink()
303  chkdosfiles()
304
305  # Should be run from the toplevel
306  configDir = os.path.abspath('config')
307  bsDir     = os.path.join(configDir, 'BuildSystem')
308  if not os.path.isdir(configDir):
309    raise RuntimeError('Run configure from $PETSC_DIR, not '+os.path.abspath('.'))
310  sys.path.insert(0, bsDir)
311  sys.path.insert(0, configDir)
312  import config.base
313  import config.framework
314  import cPickle
315
316  framework = None
317  try:
318    framework = config.framework.Framework(['--configModules=PETSc.Configure','--optionsModule=config.compilerOptions']+sys.argv[1:], loadArgDB = 0)
319    framework.setup()
320    framework.logPrint('\n'.join(extraLogs))
321    framework.configure(out = sys.stdout)
322    framework.storeSubstitutions(framework.argDB)
323    framework.argDB['configureCache'] = cPickle.dumps(framework)
324    framework.printSummary()
325    framework.argDB.save(force = True)
326    framework.logClear()
327    print_final_timestamp(framework)
328    framework.closeLog()
329    try:
330      move_configure_log(framework)
331    except:
332      # perhaps print an error about unable to shuffle logs?
333      pass
334    return 0
335  except (RuntimeError, config.base.ConfigureSetupError), e:
336    emsg = str(e)
337    if not emsg.endswith('\n'): emsg = emsg+'\n'
338    msg ='*******************************************************************************\n'\
339    +'         UNABLE to CONFIGURE with GIVEN OPTIONS    (see configure.log for details):\n' \
340    +'-------------------------------------------------------------------------------\n'  \
341    +emsg+'*******************************************************************************\n'
342    se = ''
343  except (TypeError, ValueError), e:
344    emsg = str(e)
345    if not emsg.endswith('\n'): emsg = emsg+'\n'
346    msg ='*******************************************************************************\n'\
347    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
348    +'-------------------------------------------------------------------------------\n'  \
349    +emsg+'*******************************************************************************\n'
350    se = ''
351  except ImportError, e :
352    emsg = str(e)
353    if not emsg.endswith('\n'): emsg = emsg+'\n'
354    msg ='*******************************************************************************\n'\
355    +'                     UNABLE to FIND MODULE for ./configure \n' \
356    +'-------------------------------------------------------------------------------\n'  \
357    +emsg+'*******************************************************************************\n'
358    se = ''
359  except OSError, e :
360    emsg = str(e)
361    if not emsg.endswith('\n'): emsg = emsg+'\n'
362    msg ='*******************************************************************************\n'\
363    +'                    UNABLE to EXECUTE BINARIES for ./configure \n' \
364    +'-------------------------------------------------------------------------------\n'  \
365    +emsg+'*******************************************************************************\n'
366    se = ''
367  except SystemExit, e:
368    if e.code is None or e.code == 0:
369      return
370    msg ='*******************************************************************************\n'\
371    +'         CONFIGURATION FAILURE  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
372    +'*******************************************************************************\n'
373    se  = str(e)
374  except Exception, e:
375    msg ='*******************************************************************************\n'\
376    +'        CONFIGURATION CRASH  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
377    +'*******************************************************************************\n'
378    se  = str(e)
379
380  print msg
381  if not framework is None:
382    framework.logClear()
383    if hasattr(framework, 'log'):
384      try:
385        if hasattr(framework,'compilerDefines'):
386          framework.log.write('**** Configure header '+framework.compilerDefines+' ****\n')
387          framework.outputHeader(framework.log)
388        if hasattr(framework,'compilerFixes'):
389          framework.log.write('**** C specific Configure header '+framework.compilerFixes+' ****\n')
390          framework.outputCHeader(framework.log)
391      except Exception, e:
392        framework.log.write('Problem writing headers to log: '+str(e))
393      import traceback
394      try:
395        framework.log.write(msg+se)
396        traceback.print_tb(sys.exc_info()[2], file = framework.log)
397        print_final_timestamp(framework)
398        if hasattr(framework,'log'): framework.log.close()
399        move_configure_log(framework)
400      except:
401        pass
402      sys.exit(1)
403  else:
404    print se
405    import traceback
406    traceback.print_tb(sys.exc_info()[2])
407  if hasattr(framework,'log'): framework.log.close()
408
409if __name__ == '__main__':
410  petsc_configure([])
411
412