xref: /petsc/config/configure.py (revision 2205254efee3a00a594e5e2a3a70f74dcb40bc03)
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. Assuming petsc-dev and downloading from https://bitbucket.org/petsc/buildsystem/get/tip.tar.gz'
37    downloadPackage('https://bitbucket.org/petsc/buildsystem/get/tip.tar.gz', 'BuildSystem.tar.gz', configDir)
38  else:
39    print '++ Mercurial clone found. URL : ' + output
40    bsurl = output.replace('petsc-dev','buildsystem').replace('petsc-','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] >= 4:
56  print '*** You must have Python2 version 2.4 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/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 chkdosfiles():
116  if not os.path.exists('/usr/bin/cygcheck.exe'): return
117  (status,output) = commands.getstatusoutput('hg showconfig paths.default')
118  if not status and output: return
119  # cygwin - but not a hg clone - so check files in bin dir
120  (status,output) = commands.getstatusoutput('file bin/*')
121  if status:
122    print '==============================================================================='
123    print ' *** Incomplete cygwin install? command "file" not found!                    **'
124    print '==============================================================================='
125    return
126  if output.find('with CRLF line terminators') >= 0:
127    print '==============================================================================='
128    print ' *** Scripts are in DOS mode. Was winzip used instead of tar? Converting.......'
129    print '==============================================================================='
130    (status,output) = commands.getstatusoutput('dos2unix bin/*')
131    if status:
132      print '==============================================================================='
133      print ' *** Incomplete cygwin install? command "dos2unix" not found!                **'
134      print '==============================================================================='
135  return
136
137def chkcygwinlink():
138  if os.path.exists('/usr/bin/cygcheck.exe') and os.path.exists('/usr/bin/link.exe') and chkwinf90():
139      if '--ignore-cygwin-link' in sys.argv: return 0
140      print '==============================================================================='
141      print ' *** Cygwin /usr/bin/link detected! Compiles with CVF/Intel f90 can break!  **'
142      print ' *** To workarround do: "mv /usr/bin/link.exe /usr/bin/link-cygwin.exe"     **'
143      print ' *** Or to ignore this check, use configure option: --ignore-cygwin-link    **'
144      print '==============================================================================='
145      sys.exit(3)
146  return 0
147
148def chkbrokencygwin():
149  if os.path.exists('/usr/bin/cygcheck.exe'):
150    buf = os.popen('/usr/bin/cygcheck.exe -c cygwin').read()
151    if buf.find('1.5.11-1') > -1:
152      print '==============================================================================='
153      print ' *** cygwin-1.5.11-1 detected. ./configure fails with this version ***'
154      print ' *** Please upgrade to cygwin-1.5.12-1 or newer version. This can  ***'
155      print ' *** be done by running cygwin-setup, selecting "next" all the way.***'
156      print '==============================================================================='
157      sys.exit(3)
158  return 0
159
160def chkcygwinpython():
161  if os.path.exists('/usr/bin/cygcheck.exe') and sys.platform == 'cygwin' :
162    sys.argv.append('--useThreads=0')
163    extraLogs.append('''\
164===============================================================================
165** Cygwin-python detected. Threads do not work correctly. ***
166** Disabling thread usage for this run of ./configure *******
167===============================================================================''')
168  return 0
169
170def chkrhl9():
171  if os.path.exists('/etc/redhat-release'):
172    try:
173      file = open('/etc/redhat-release','r')
174      buf = file.read()
175      file.close()
176    except:
177      # can't read file - assume dangerous RHL9
178      buf = 'Shrike'
179    if buf.find('Shrike') > -1:
180      sys.argv.append('--useThreads=0')
181      extraLogs.append('''\
182==============================================================================
183   *** RHL9 detected. Threads do not work correctly with this distribution ***
184   ****** Disabling thread usage for this run of ./configure *********
185===============================================================================''')
186  return 0
187
188def check_broken_configure_log_links():
189  '''Sometime symlinks can get broken if the original files are deleted. Delete such broken links'''
190  import os
191  for logfile in ['configure.log','configure.log.bkp']:
192    if os.path.islink(logfile) and not os.path.isfile(logfile): os.remove(logfile)
193  return
194
195def move_configure_log(framework):
196  '''Move configure.log to PETSC_ARCH/conf - and update configure.log.bkp in both locations appropriately'''
197  global petsc_arch
198
199  if hasattr(framework,'arch'): petsc_arch = framework.arch
200  if hasattr(framework,'logName'): curr_file = framework.logName
201  else: curr_file = 'configure.log'
202
203  if petsc_arch:
204    import shutil
205    import os
206
207    # Just in case - confdir is not created
208    conf_dir = os.path.join(petsc_arch,'conf')
209    if not os.path.isdir(petsc_arch): os.mkdir(petsc_arch)
210    if not os.path.isdir(conf_dir): os.mkdir(conf_dir)
211
212    curr_bkp  = curr_file + '.bkp'
213    new_file  = os.path.join(conf_dir,curr_file)
214    new_bkp   = new_file + '.bkp'
215
216    # Keep backup in $PETSC_ARCH/conf location
217    if os.path.isfile(new_bkp): os.remove(new_bkp)
218    if os.path.isfile(new_file): os.rename(new_file,new_bkp)
219    if os.path.isfile(curr_file):
220      shutil.copyfile(curr_file,new_file)
221      os.remove(curr_file)
222    if os.path.isfile(new_file): os.symlink(new_file,curr_file)
223    # If the old bkp is using the same PETSC_ARCH/conf - then update bkp link
224    if os.path.realpath(curr_bkp) == os.path.realpath(new_file):
225      if os.path.isfile(curr_bkp): os.remove(curr_bkp)
226      if os.path.isfile(new_bkp): os.symlink(new_bkp,curr_bkp)
227  return
228
229def petsc_configure(configure_options):
230  try:
231    petscdir = os.environ['PETSC_DIR']
232    sys.path.append(os.path.join(petscdir,'bin'))
233    import petscnagupgrade
234    file     = os.path.join(petscdir,'.nagged')
235    if not petscnagupgrade.naggedtoday(file):
236      petscnagupgrade.currentversion(petscdir)
237  except:
238    pass
239  print '==============================================================================='
240  print '             Configuring PETSc to compile on your system                       '
241  print '==============================================================================='
242
243  try:
244    # Command line arguments take precedence (but don't destroy argv[0])
245    sys.argv = sys.argv[:1] + configure_options + sys.argv[1:]
246    check_for_option_mistakes(sys.argv)
247    check_for_option_changed(sys.argv)
248  except (TypeError, ValueError), e:
249    emsg = str(e)
250    if not emsg.endswith('\n'): emsg = emsg+'\n'
251    msg ='*******************************************************************************\n'\
252    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
253    +'-------------------------------------------------------------------------------\n'  \
254    +emsg+'*******************************************************************************\n'
255    sys.exit(msg)
256  # check PETSC_ARCH
257  check_petsc_arch(sys.argv)
258  check_broken_configure_log_links()
259
260  # support a few standard configure option types
261  for l in range(0,len(sys.argv)):
262    name = sys.argv[l]
263    if name.find('enable-') >= 0:
264      if name.find('=') == -1:
265        sys.argv[l] = name.replace('enable-','with-')+'=1'
266      else:
267        head, tail = name.split('=', 1)
268        sys.argv[l] = head.replace('enable-','with-')+'='+tail
269    if name.find('disable-') >= 0:
270      if name.find('=') == -1:
271        sys.argv[l] = name.replace('disable-','with-')+'=0'
272      else:
273        head, tail = name.split('=', 1)
274        if tail == '1': tail = '0'
275        sys.argv[l] = head.replace('disable-','with-')+'='+tail
276    if name.find('without-') >= 0:
277      if name.find('=') == -1:
278        sys.argv[l] = name.replace('without-','with-')+'=0'
279      else:
280        head, tail = name.split('=', 1)
281        if tail == '1': tail = '0'
282        sys.argv[l] = head.replace('without-','with-')+'='+tail
283
284  # Check for broken cygwin
285  chkbrokencygwin()
286  # Disable threads on RHL9
287  chkrhl9()
288  # Threads don't work for cygwin & python...
289  chkcygwinpython()
290  chkcygwinlink()
291  chkdosfiles()
292
293  # Should be run from the toplevel
294  configDir = os.path.abspath('config')
295  bsDir     = os.path.join(configDir, 'BuildSystem')
296  if not os.path.isdir(configDir):
297    raise RuntimeError('Run configure from $PETSC_DIR, not '+os.path.abspath('.'))
298  if not os.path.isdir(bsDir): getBuildSystem(configDir,bsDir)
299  sys.path.insert(0, bsDir)
300  sys.path.insert(0, configDir)
301  import config.base
302  import config.framework
303  import cPickle
304
305  framework = None
306  try:
307    framework = config.framework.Framework(['--configModules=PETSc.Configure','--optionsModule=PETSc.compilerOptions']+sys.argv[1:], loadArgDB = 0)
308    framework.setup()
309    framework.logPrint('\n'.join(extraLogs))
310    framework.configure(out = sys.stdout)
311    framework.storeSubstitutions(framework.argDB)
312    framework.argDB['configureCache'] = cPickle.dumps(framework)
313    framework.printSummary()
314    framework.argDB.save(force = True)
315    framework.logClear()
316    framework.closeLog()
317    try:
318      move_configure_log(framework)
319    except:
320      # perhaps print an error about unable to shuffle logs?
321      pass
322    return 0
323  except (RuntimeError, config.base.ConfigureSetupError), e:
324    emsg = str(e)
325    if not emsg.endswith('\n'): emsg = emsg+'\n'
326    msg ='*******************************************************************************\n'\
327    +'         UNABLE to CONFIGURE with GIVEN OPTIONS    (see configure.log for details):\n' \
328    +'-------------------------------------------------------------------------------\n'  \
329    +emsg+'*******************************************************************************\n'
330    se = ''
331  except (TypeError, ValueError), e:
332    emsg = str(e)
333    if not emsg.endswith('\n'): emsg = emsg+'\n'
334    msg ='*******************************************************************************\n'\
335    +'                ERROR in COMMAND LINE ARGUMENT to ./configure \n' \
336    +'-------------------------------------------------------------------------------\n'  \
337    +emsg+'*******************************************************************************\n'
338    se = ''
339  except ImportError, e :
340    emsg = str(e)
341    if not emsg.endswith('\n'): emsg = emsg+'\n'
342    msg ='*******************************************************************************\n'\
343    +'                     UNABLE to FIND MODULE for ./configure \n' \
344    +'-------------------------------------------------------------------------------\n'  \
345    +emsg+'*******************************************************************************\n'
346    se = ''
347  except OSError, e :
348    emsg = str(e)
349    if not emsg.endswith('\n'): emsg = emsg+'\n'
350    msg ='*******************************************************************************\n'\
351    +'                    UNABLE to EXECUTE BINARIES for ./configure \n' \
352    +'-------------------------------------------------------------------------------\n'  \
353    +emsg+'*******************************************************************************\n'
354    se = ''
355  except SystemExit, e:
356    if e.code is None or e.code == 0:
357      return
358    msg ='*******************************************************************************\n'\
359    +'         CONFIGURATION FAILURE  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
360    +'*******************************************************************************\n'
361    se  = str(e)
362  except Exception, e:
363    msg ='*******************************************************************************\n'\
364    +'        CONFIGURATION CRASH  (Please send configure.log to petsc-maint@mcs.anl.gov)\n' \
365    +'*******************************************************************************\n'
366    se  = str(e)
367
368  print msg
369  if not framework is None:
370    framework.logClear()
371    if hasattr(framework, 'log'):
372      try:
373        framework.log.write('**** Configure header conftest.h ****\n')
374        framework.outputHeader(framework.log)
375        framework.log.write('**** C specific Configure header conffix.h ****\n')
376        framework.outputCHeader(framework.log)
377      except Exception, e:
378        framework.log.write('Problem writing headers to log: '+str(e))
379      import traceback
380      try:
381        framework.log.write(msg+se)
382        traceback.print_tb(sys.exc_info()[2], file = framework.log)
383        if hasattr(framework,'log'): framework.log.close()
384        move_configure_log(framework)
385      except:
386        pass
387      sys.exit(1)
388  else:
389    print se
390    import traceback
391    traceback.print_tb(sys.exc_info()[2])
392  if hasattr(framework,'log'): framework.log.close()
393
394if __name__ == '__main__':
395  petsc_configure([])
396
397