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