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