xref: /petsc/config/configure.py (revision 7cf18bfc0af3bd20f57ca1ab9dbfc3d774cdee5d)
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
9import urllib
10import tarfile
11
12def untar(tar, path = '.', leading = ''):
13  if leading:
14    entries = [t.name for t in tar.getmembers()]
15    prefix = os.path.commonprefix(entries)
16    if prefix:
17      for tarinfo in tar.getmembers():
18        tail = tarinfo.name.split(prefix, 1)[1]
19        tarinfo.name = os.path.join(leading, tail)
20  for tarinfo in tar.getmembers():
21    tar.extract(tarinfo, path)
22  return
23
24def downloadPackage(url, filename, targetDirname):
25  '''Download the tarball for a package at url, save it as filename, and untar it into targetDirname'''
26  filename, headers = urllib.urlretrieve(url, filename)
27  tar = tarfile.open(filename, 'r:gz')
28  untar(tar, targetDirname, leading = filename.split('.')[0])
29  return
30
31def getBuildSystem(configDir,bsDir):
32  print '==============================================================================='
33  print '''++ Could not locate BuildSystem in %s.''' % configDir
34  (status,output) = commands.getstatusoutput('hg showconfig paths.default')
35  if status or not output:
36    print '++ Mercurial clone not found. Downloading it from http://petsc.cs.iit.edu/petsc/BuildSystem/archive/tip.tar.gz'
37    downloadPackage('http://petsc.cs.iit.edu/petsc/BuildSystem/archive/tip.tar.gz', 'BuildSystem.tar.gz', configDir)
38  else:
39    print '++ Mercurial clone found. URL : ' + output
40    bsurl = output.replace('petsc-dev','BuildSystem').replace('releases/petsc-','releases/BuildSystem-')
41    print '++ Using: hg clone '+ bsurl +' '+ bsDir
42    (status,output) = commands.getstatusoutput('hg clone '+ bsurl +' '+ bsDir)
43    if status:
44      print '++ Unable to clone BuildSystem. Please clone manually'
45      print '==============================================================================='
46      sys.exit(3)
47  print '==============================================================================='
48  return
49
50
51# Use en_US as language so that BuildSystem parses compiler messages in english
52if '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'
53if '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'
54
55if not hasattr(sys, 'version_info') or not sys.version_info[0] == 2 or not sys.version_info[1] >= 3:
56  print '*** You must have Python2 version 2.3 or higher to run ./configure        *****'
57  print '*          Python is easy to install for end users or sys-admin.              *'
58  print '*                  http://www.python.org/download/                            *'
59  print '*                                                                             *'
60  print '*           You CANNOT configure PETSc without Python                         *'
61  print '*   http://www.mcs.anl.gov/petsc/petsc-as/documentation/installation.html     *'
62  print '*******************************************************************************'
63  sys.exit(4)
64
65def check_for_option_mistakes(opts):
66  for opt in opts[1:]:
67    name = opt.split('=')[0]
68    if name.find('_') >= 0:
69      exception = False
70      for exc in ['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']:
71        if name.find(exc) >= 0:
72          exception = True
73      if not exception:
74        raise ValueError('The option '+name+' should probably be '+name.replace('_', '-'));
75    if opt.find('=') >=0:
76      optval = opt.split('=')[1]
77      if optval == 'ifneeded':
78        raise ValueError('The option '+opt+' should probably be '+opt.replace('ifneeded', '1'));
79  return
80
81def check_for_option_changed(opts):
82# Document changes in command line options here.
83  optMap = [('c-blas-lapack','f2cblaslapack')]
84  for opt in opts[1:]:
85    optname = opt.split('=')[0].strip('-')
86    for oldname,newname in optMap:
87      if optname.find(oldname) >=0:
88        raise ValueError('The option '+opt+' should probably be '+opt.replace(oldname,newname))
89  return
90
91def check_petsc_arch(opts):
92  # If PETSC_ARCH not specified - use script name (if not configure.py)
93  global petsc_arch
94  found = 0
95  for name in opts:
96    if name.find('PETSC_ARCH=') >= 0:
97      petsc_arch=name.split('=')[1]
98      found = 1
99      break
100  # If not yet specified - use the filename of script
101  if not found:
102      filename = os.path.basename(sys.argv[0])
103      if not filename.startswith('configure') and not filename.startswith('reconfigure') and not filename.startswith('setup'):
104        petsc_arch=os.path.splitext(os.path.basename(sys.argv[0]))[0]
105        useName = 'PETSC_ARCH='+petsc_arch
106        opts.append(useName)
107  return 0
108
109def chkwinf90():
110  for arg in sys.argv:
111    if (arg.find('win32fe') >= 0 and (arg.find('f90') >=0 or arg.find('ifort') >=0)):
112      return 1
113  return 0
114
115def chkcygwinlink():
116  if os.path.exists('/usr/bin/cygcheck.exe') and os.path.exists('/usr/bin/link.exe') and chkwinf90():
117      if '--ignore-cygwin-link' in sys.argv: return 0
118      print '==============================================================================='
119      print ' *** Cygwin /usr/bin/link detected! Compiles with CVF/Intel f90 can break!  **'
120      print ' *** To workarround do: "mv /usr/bin/link.exe /usr/bin/link-cygwin.exe"     **'
121      print ' *** Or to ignore this check, use configure option: --ignore-cygwin-link    **'
122      print '==============================================================================='
123      sys.exit(3)
124  return 0
125
126def chkbrokencygwin():
127  if os.path.exists('/usr/bin/cygcheck.exe'):
128    buf = os.popen('/usr/bin/cygcheck.exe -c cygwin').read()
129    if buf.find('1.5.11-1') > -1:
130      print '==============================================================================='
131      print ' *** cygwin-1.5.11-1 detected. ./configure fails with this version ***'
132      print ' *** Please upgrade to cygwin-1.5.12-1 or newer version. This can  ***'
133      print ' *** be done by running cygwin-setup, selecting "next" all the way.***'
134      print '==============================================================================='
135      sys.exit(3)
136  return 0
137
138def chkcygwinpython():
139  if os.path.exists('/usr/bin/cygcheck.exe') and sys.platform == 'cygwin' :
140    sys.argv.append('--useThreads=0')
141    extraLogs.append('''\
142===============================================================================
143** Cygwin-python detected. Threads do not work correctly. ***
144** Disabling thread usage for this run of ./configure *******
145===============================================================================''')
146  return 0
147
148def chkrhl9():
149  if os.path.exists('/etc/redhat-release'):
150    try:
151      file = open('/etc/redhat-release','r')
152      buf = file.read()
153      file.close()
154    except:
155      # can't read file - assume dangerous RHL9
156      buf = 'Shrike'
157    if buf.find('Shrike') > -1:
158      sys.argv.append('--useThreads=0')
159      extraLogs.append('''\
160==============================================================================
161   *** RHL9 detected. Threads do not work correctly with this distribution ***
162   ****** Disabling thread usage for this run of ./configure *********
163===============================================================================''')
164  return 0
165
166def check_broken_configure_log_links():
167  '''Sometime symlinks can get broken if the original files are deleted. Delete such broken links'''
168  import os
169  for logfile in ['configure.log','configure.log.bkp']:
170    if os.path.islink(logfile) and not os.path.isfile(logfile): os.remove(logfile)
171  return
172
173def move_configure_log(framework):
174  '''Move configure.log to PETSC_ARCH/conf - and update configure.log.bkp in both locations appropriately'''
175  global petsc_arch
176
177  if hasattr(framework,'arch'): petsc_arch = framework.arch
178  if hasattr(framework,'logName'): curr_file = framework.logName
179  else: curr_file = 'configure.log'
180
181  if petsc_arch:
182    import shutil
183    import os
184
185    # Just in case - confdir is not created
186    conf_dir = os.path.join(petsc_arch,'conf')
187    if not os.path.isdir(petsc_arch): os.mkdir(petsc_arch)
188    if not os.path.isdir(conf_dir): os.mkdir(conf_dir)
189
190    curr_bkp  = curr_file + '.bkp'
191    new_file  = os.path.join(conf_dir,curr_file)
192    new_bkp   = new_file + '.bkp'
193
194    # Keep backup in $PETSC_ARCH/conf location
195    if os.path.isfile(new_bkp): os.remove(new_bkp)
196    if os.path.isfile(new_file): os.rename(new_file,new_bkp)
197    if os.path.isfile(curr_file):
198      shutil.copyfile(curr_file,new_file)
199      os.remove(curr_file)
200    if os.path.isfile(new_file): os.symlink(new_file,curr_file)
201    # If the old bkp is using the same PETSC_ARCH/conf - then update bkp link
202    if os.path.realpath(curr_bkp) == os.path.realpath(new_file):
203      if os.path.isfile(curr_bkp): os.remove(curr_bkp)
204      if os.path.isfile(new_bkp): os.symlink(new_bkp,curr_bkp)
205  return
206
207def petsc_configure(configure_options):
208  print '==============================================================================='
209  print '             Configuring PETSc to compile on your system                       '
210  print '==============================================================================='
211
212  try:
213    # Command line arguments take precedence (but don't destroy argv[0])
214    sys.argv = sys.argv[:1] + configure_options + sys.argv[1:]
215    check_for_option_mistakes(sys.argv)
216    check_for_option_changed(sys.argv)
217  except (TypeError, ValueError), e:
218    emsg = str(e)
219    if not emsg.endswith('\n'): emsg = emsg+'\n'
220    msg ='*******************************************************************************\n'\
221    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
222    +'-------------------------------------------------------------------------------\n'  \
223    +emsg+'*******************************************************************************\n'
224    sys.exit(msg)
225  # check PETSC_ARCH
226  check_petsc_arch(sys.argv)
227  check_broken_configure_log_links()
228
229  # support a few standard configure option types
230  for l in range(0,len(sys.argv)):
231    name = sys.argv[l]
232    if name.find('enable-') >= 0:
233      if name.find('=') == -1:
234        sys.argv[l] = name.replace('enable-','with-')+'=1'
235      else:
236        head, tail = name.split('=', 1)
237        sys.argv[l] = head.replace('enable-','with-')+'='+tail
238    if name.find('disable-') >= 0:
239      if name.find('=') == -1:
240        sys.argv[l] = name.replace('disable-','with-')+'=0'
241      else:
242        head, tail = name.split('=', 1)
243        if tail == '1': tail = '0'
244        sys.argv[l] = head.replace('disable-','with-')+'='+tail
245    if name.find('without-') >= 0:
246      if name.find('=') == -1:
247        sys.argv[l] = name.replace('without-','with-')+'=0'
248      else:
249        head, tail = name.split('=', 1)
250        if tail == '1': tail = '0'
251        sys.argv[l] = head.replace('without-','with-')+'='+tail
252
253  # Check for broken cygwin
254  chkbrokencygwin()
255  # Disable threads on RHL9
256  chkrhl9()
257  # Threads don't work for cygwin & python...
258  chkcygwinpython()
259  chkcygwinlink()
260
261  # Should be run from the toplevel
262  configDir = os.path.abspath('config')
263  bsDir     = os.path.join(configDir, 'BuildSystem')
264  if not os.path.isdir(configDir):
265    raise RuntimeError('Run configure from $PETSC_DIR, not '+os.path.abspath('.'))
266  if not os.path.isdir(bsDir): getBuildSystem(configDir,bsDir)
267  sys.path.insert(0, bsDir)
268  sys.path.insert(0, configDir)
269  import config.base
270  import config.framework
271  import cPickle
272
273  framework = None
274  try:
275    framework = config.framework.Framework(['--configModules=PETSc.Configure','--optionsModule=PETSc.compilerOptions']+sys.argv[1:], loadArgDB = 0)
276    framework.setup()
277    framework.logPrint('\n'.join(extraLogs))
278    framework.configure(out = sys.stdout)
279    framework.storeSubstitutions(framework.argDB)
280    framework.argDB['configureCache'] = cPickle.dumps(framework)
281    import PETSc.packages
282    for i in framework.packages:
283      if hasattr(i,'postProcess'):
284        i.postProcess()
285    framework.printSummary()
286    framework.argDB.save(force = True)
287    framework.logClear()
288    framework.closeLog()
289    try:
290      move_configure_log(framework)
291    except:
292      # perhaps print an error about unable to shuffle logs?
293      pass
294    return 0
295  except (RuntimeError, config.base.ConfigureSetupError), e:
296    emsg = str(e)
297    if not emsg.endswith('\n'): emsg = emsg+'\n'
298    msg ='*******************************************************************************\n'\
299    +'         UNABLE to CONFIGURE with GIVEN OPTIONS    (see configure.log for details):\n' \
300    +'-------------------------------------------------------------------------------\n'  \
301    +emsg+'*******************************************************************************\n'
302    se = ''
303  except (TypeError, ValueError), e:
304    emsg = str(e)
305    if not emsg.endswith('\n'): emsg = emsg+'\n'
306    msg ='*******************************************************************************\n'\
307    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
308    +'-------------------------------------------------------------------------------\n'  \
309    +emsg+'*******************************************************************************\n'
310    se = ''
311  except ImportError, e :
312    emsg = str(e)
313    if not emsg.endswith('\n'): emsg = emsg+'\n'
314    msg ='*******************************************************************************\n'\
315    +'                     UNABLE to FIND MODULE for ./configure \n' \
316    +'-------------------------------------------------------------------------------\n'  \
317    +emsg+'*******************************************************************************\n'
318    se = ''
319  except OSError, e :
320    emsg = str(e)
321    if not emsg.endswith('\n'): emsg = emsg+'\n'
322    msg ='*******************************************************************************\n'\
323    +'                    UNABLE to EXECUTE BINARIES for ./configure \n' \
324    +'-------------------------------------------------------------------------------\n'  \
325    +emsg+'*******************************************************************************\n'
326    se = ''
327  except SystemExit, e:
328    if e.code is None or e.code == 0:
329      return
330    msg ='*******************************************************************************\n'\
331    +'         CONFIGURATION FAILURE  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
332    +'*******************************************************************************\n'
333    se  = str(e)
334  except Exception, e:
335    msg ='*******************************************************************************\n'\
336    +'        CONFIGURATION CRASH  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
337    +'*******************************************************************************\n'
338    se  = str(e)
339
340  print msg
341  if not framework is None:
342    framework.logClear()
343    if hasattr(framework, 'log'):
344      import traceback
345      try:
346        framework.log.write(msg+se)
347        traceback.print_tb(sys.exc_info()[2], file = framework.log)
348        if hasattr(framework,'log'): framework.log.close()
349        move_configure_log(framework)
350      except:
351        pass
352      sys.exit(1)
353  else:
354    print se
355    import traceback
356    traceback.print_tb(sys.exc_info()[2])
357  if hasattr(framework,'log'): framework.log.close()
358
359if __name__ == '__main__':
360  petsc_configure([])
361
362