Salome HOME
correction coquille
[tools/sat.git] / src / compilation.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2013  CEA/DEN
4 #
5 #  This library is free software; you can redistribute it and/or
6 #  modify it under the terms of the GNU Lesser General Public
7 #  License as published by the Free Software Foundation; either
8 #  version 2.1 of the License.
9 #
10 #  This library is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #  Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public
16 #  License along with this library; if not, write to the Free Software
17 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18
19 import os
20 import subprocess
21 import sys
22 import shutil
23 import glob
24
25 import src
26
27 C_COMPILE_ENV_LIST = ["CC",
28                       "CXX",
29                       "F77",
30                       "CFLAGS",
31                       "CXXFLAGS",
32                       "LIBS",
33                       "LDFLAGS"]
34
35 class Builder:
36     """Class to handle all construction steps, like cmake, configure, make, ...
37     """
38     def __init__(self,
39                  config,
40                  logger,
41                  product_info,
42                  options = src.options.OptResult(),
43                  check_src=True):
44         self.config = config
45         self.logger = logger
46         self.options = options
47         self.product_info = product_info
48         self.build_dir = src.Path(self.product_info.build_dir)
49         self.source_dir = src.Path(self.product_info.source_dir)
50         self.install_dir = src.Path(self.product_info.install_dir)
51         self.header = ""
52         self.debug_mode = False
53         if "debug" in self.product_info and self.product_info.debug == "yes":
54             self.debug_mode = True
55         self.verbose_mode = False
56         if "verbose" in self.product_info and self.product_info.verbose == "yes":
57             self.verbose_mode = True
58
59     ##
60     # Shortcut method to log in log file.
61     def log(self, text, level, showInfo=True):
62         self.logger.write(text, level, showInfo)
63         self.logger.logTxtFile.write(src.printcolors.cleancolor(text))
64         self.logger.flush()
65
66     ##
67     # Shortcut method to log a command.
68     def log_command(self, command):
69         self.log("> %s\n" % command, 5)
70
71     ##
72     # Prepares the environment.
73     # Build two environment: one for building and one for testing (launch).
74     def prepare(self):
75
76         if not self.build_dir.exists():
77             # create build dir
78             self.build_dir.make()
79
80         self.log('  build_dir   = %s\n' % str(self.build_dir), 4)
81         self.log('  install_dir = %s\n' % str(self.install_dir), 4)
82         self.log('\n', 4)
83
84         # add products in depend and opt_depend list recursively
85         environ_info = src.product.get_product_dependencies(self.config,
86                                                             self.product_info)
87         #environ_info.append(self.product_info.name)
88
89         # create build environment
90         self.build_environ = src.environment.SalomeEnviron(self.config,
91                                       src.environment.Environ(dict(os.environ)),
92                                       True)
93         self.build_environ.silent = (self.config.USER.output_verbose_level < 5)
94         self.build_environ.set_full_environ(self.logger, environ_info)
95         
96         # create runtime environment
97         self.launch_environ = src.environment.SalomeEnviron(self.config,
98                                       src.environment.Environ(dict(os.environ)),
99                                       False)
100         self.launch_environ.silent = True # no need to show here
101         self.launch_environ.set_full_environ(self.logger, environ_info)
102
103         for ee in C_COMPILE_ENV_LIST:
104             vv = self.build_environ.get(ee)
105             if len(vv) > 0:
106                 self.log("  %s = %s\n" % (ee, vv), 4, False)
107
108         return 0
109
110     ##
111     # Runs cmake with the given options.
112     def cmake(self, options=""):
113
114         cmake_option = options
115         # cmake_option +=' -DCMAKE_VERBOSE_MAKEFILE=ON -DSALOME_CMAKE_DEBUG=ON'
116         if 'cmake_options' in self.product_info:
117             cmake_option += " %s " % " ".join(
118                                         self.product_info.cmake_options.split())
119
120         # add debug option
121         if self.debug_mode:
122             cmake_option += " -DCMAKE_BUILD_TYPE=Debug"
123         else :
124             cmake_option += " -DCMAKE_BUILD_TYPE=Release"
125
126         # add verbose option if specified in application for this product.
127         if self.verbose_mode:
128             cmake_option += " -DCMAKE_VERBOSE_MAKEFILE=ON"
129
130         # In case CMAKE_GENERATOR is defined in environment, 
131         # use it in spite of automatically detect it
132         if 'cmake_generator' in self.config.APPLICATION:
133             cmake_option += " -DCMAKE_GENERATOR=\"%s\"" \
134                                        % self.config.APPLICATION.cmake_generator
135         command = ("cmake %s -DCMAKE_INSTALL_PREFIX=%s %s" %
136                             (cmake_option, self.install_dir, self.source_dir))
137
138         self.log_command(command)
139         # for key in sorted(self.build_environ.environ.environ.keys()):
140             # print key, "  ", self.build_environ.environ.environ[key]
141         res = subprocess.call(command,
142                               shell=True,
143                               cwd=str(self.build_dir),
144                               env=self.build_environ.environ.environ,
145                               stdout=self.logger.logTxtFile,
146                               stderr=subprocess.STDOUT)
147
148         self.put_txt_log_in_appli_log_dir("cmake")
149         if res == 0:
150             return res
151         else:
152             return 1
153
154     ##
155     # Runs build_configure with the given options.
156     def build_configure(self, options=""):
157
158         if 'buildconfigure_options' in self.product_info:
159             options += " %s " % self.product_info.buildconfigure_options
160
161         command = str('%s/build_configure') % (self.source_dir)
162         command = command + " " + options
163         self.log_command(command)
164
165         res = subprocess.call(command,
166                               shell=True,
167                               cwd=str(self.build_dir),
168                               env=self.build_environ.environ.environ,
169                               stdout=self.logger.logTxtFile,
170                               stderr=subprocess.STDOUT)
171         self.put_txt_log_in_appli_log_dir("build_configure")
172         if res == 0:
173             return res
174         else:
175             return 1
176
177     ##
178     # Runs configure with the given options.
179     def configure(self, options=""):
180
181         if 'configure_options' in self.product_info:
182             options += " %s " % self.product_info.configure_options
183
184         command = "%s/configure --prefix=%s" % (self.source_dir,
185                                                 str(self.install_dir))
186
187         command = command + " " + options
188         self.log_command(command)
189
190         res = subprocess.call(command,
191                               shell=True,
192                               cwd=str(self.build_dir),
193                               env=self.build_environ.environ.environ,
194                               stdout=self.logger.logTxtFile,
195                               stderr=subprocess.STDOUT)
196         
197         self.put_txt_log_in_appli_log_dir("configure")
198         if res == 0:
199             return res
200         else:
201             return 1
202
203     def hack_libtool(self):
204         if not os.path.exists(str(self.build_dir + 'libtool')):
205             return
206
207         lf = open(os.path.join(str(self.build_dir), "libtool"), 'r')
208         for line in lf.readlines():
209             if 'hack_libtool' in line:
210                 return
211
212         # fix libtool by replacing CC="<compil>" with hack_libtool function
213         hack_command='''sed -i "s%^CC=\\"\(.*\)\\"%hack_libtool() { \\n\\
214 if test \\"\$(echo \$@ | grep -E '\\\\\\-L/usr/lib(/../lib)?(64)? ')\\" == \\\"\\\" \\n\\
215   then\\n\\
216     cmd=\\"\\1 \$@\\"\\n\\
217   else\\n\\
218     cmd=\\"\\1 \\"\`echo \$@ | sed -r -e 's|(.*)-L/usr/lib(/../lib)?(64)? (.*)|\\\\\\1\\\\\\4 -L/usr/lib\\\\\\3|g'\`\\n\\
219   fi\\n\\
220   \$cmd\\n\\
221 }\\n\\
222 CC=\\"hack_libtool\\"%g" libtool'''
223
224         self.log_command(hack_command)
225         subprocess.call(hack_command,
226                         shell=True,
227                         cwd=str(self.build_dir),
228                         env=self.build_environ.environ.environ,
229                         stdout=self.logger.logTxtFile,
230                         stderr=subprocess.STDOUT)
231
232
233     ##
234     # Runs make to build the module.
235     def make(self, nb_proc, make_opt=""):
236
237         # make
238         command = 'make'
239         command = command + " -j" + str(nb_proc)
240         command = command + " " + make_opt
241         self.log_command(command)
242         res = subprocess.call(command,
243                               shell=True,
244                               cwd=str(self.build_dir),
245                               env=self.build_environ.environ.environ,
246                               stdout=self.logger.logTxtFile,
247                               stderr=subprocess.STDOUT)
248         self.put_txt_log_in_appli_log_dir("make")
249         if res == 0:
250             return res
251         else:
252             return 1
253     
254     ##
255     # Runs msbuild to build the module.
256     def wmake(self,nb_proc, opt_nb_proc = None):
257
258         hh = 'MSBUILD /m:%s' % str(nb_proc)
259         if self.debug_mode:
260             hh += " " + src.printcolors.printcWarning("DEBUG")
261         # make
262         command = 'msbuild'
263         command = command + " /maxcpucount:" + str(nb_proc)
264         if self.debug_mode:
265             command = command + " /p:Configuration=Debug  /p:Platform=x64 "
266         else:
267             command = command + " /p:Configuration=Release /p:Platform=x64 "
268         command = command + " ALL_BUILD.vcxproj"
269
270         self.log_command(command)
271         res = subprocess.call(command,
272                               shell=True,
273                               cwd=str(self.build_dir),
274                               env=self.build_environ.environ.environ,
275                               stdout=self.logger.logTxtFile,
276                               stderr=subprocess.STDOUT)
277         
278         self.put_txt_log_in_appli_log_dir("make")
279         if res == 0:
280             return res
281         else:
282             return 1
283
284     ##
285     # Runs 'make install'.
286     def install(self):
287         if src.architecture.is_windows():
288             command = 'msbuild INSTALL.vcxproj'
289             if self.debug_mode:
290                 command = command + " /p:Configuration=Debug  /p:Platform=x64 "
291             else:
292                 command = command + " /p:Configuration=Release  /p:Platform=x64 "
293         else :
294             command = 'make install'
295         self.log_command(command)
296
297         res = subprocess.call(command,
298                               shell=True,
299                               cwd=str(self.build_dir),
300                               env=self.build_environ.environ.environ,
301                               stdout=self.logger.logTxtFile,
302                               stderr=subprocess.STDOUT)
303         
304         res_check=self.check_install()
305         if res_check > 0 :
306             self.log_command("Error in sat check install - some files are not installed!")
307         self.put_txt_log_in_appli_log_dir("makeinstall")
308
309         res+=res_check
310         if res == 0:
311             return res
312         else:
313             return 1
314
315     # this function checks wether a list of file patterns (specified by check_install keyword) 
316     # exixts after the make install. The objective is to ensure the installation is complete.
317     # patterns are given relatively to the install dir of the product
318     def check_install(self):
319         res=0
320         if "check_install" in self.product_info:
321             self.log_command("Check installation of files")
322             for pattern in self.product_info.check_install:
323                 # pattern is given relatively to the install dir
324                 complete_pattern=os.path.join(self.product_info.install_dir, pattern) 
325                 self.log_command("    -> check %s" % complete_pattern)
326                 # expansion of pattern : takes into account environment variables and unix shell rules
327                 list_of_path=glob.glob(os.path.expandvars(complete_pattern))
328                 if not list_of_path:
329                     # we expect to find at least one entry, if not we consider the test failed
330                     res+=1
331                     self.logger.write("Error, sat check install failed for file pattern %s\n" % complete_pattern, 1)
332                     self.log_command("Error, sat check install failed for file pattern %s" % complete_pattern)
333         return res
334
335     ##
336     # Runs 'make_check'.
337     def check(self, command=""):
338         if src.architecture.is_windows():
339             cmd = 'msbuild RUN_TESTS.vcxproj /p:Configuration=Release  /p:Platform=x64 '
340         else :
341             if self.product_info.build_source=="autotools" :
342                 cmd = 'make check'
343             else:
344                 cmd = 'make test'
345         
346         if command:
347             cmd = command
348         
349         self.log_command(cmd)
350         self.log_command("For more detailed logs, see test logs in %s" % self.build_dir)
351
352         res = subprocess.call(cmd,
353                               shell=True,
354                               cwd=str(self.build_dir),
355                               env=self.launch_environ.environ.environ,
356                               stdout=self.logger.logTxtFile,
357                               stderr=subprocess.STDOUT)
358
359         self.put_txt_log_in_appli_log_dir("makecheck")
360         if res == 0:
361             return res
362         else:
363             return 1
364       
365     ##
366     # Performs a default build for this module.
367     def do_default_build(self,
368                          build_conf_options="",
369                          configure_options="",
370                          show_warning=True):
371         use_autotools = False
372         if 'use_autotools' in self.product_info:
373             uc = self.product_info.use_autotools
374             if uc in ['always', 'yes']: 
375                 use_autotools = True
376             elif uc == 'option': 
377                 use_autotools = self.options.autotools
378
379
380         self.use_autotools = use_autotools
381
382         use_ctest = False
383         if 'use_ctest' in self.product_info:
384             uc = self.product_info.use_ctest
385             if uc in ['always', 'yes']: 
386                 use_ctest = True
387             elif uc == 'option': 
388                 use_ctest = self.options.ctest
389
390         self.use_ctest = use_ctest
391
392         if show_warning:
393             cmd = ""
394             if use_autotools: cmd = "(autotools)"
395             if use_ctest: cmd = "(ctest)"
396             
397             self.log("\n", 4, False)
398             self.log("%(module)s: Run default compilation method %(cmd)s\n" % \
399                 { "module": self.module, "cmd": cmd }, 4)
400
401         if use_autotools:
402             if not self.prepare(): return self.get_result()
403             if not self.build_configure(
404                                    build_conf_options): return self.get_result()
405             if not self.configure(configure_options): return self.get_result()
406             if not self.make(): return self.get_result()
407             if not self.install(): return self.get_result()
408             if not self.clean(): return self.get_result()
409            
410         else: # CMake
411             if self.config.VARS.dist_name=='Win':
412                 if not self.wprepare(): return self.get_result()
413                 if not self.cmake(): return self.get_result()
414                 if not self.wmake(): return self.get_result()
415                 if not self.install(): return self.get_result()
416                 if not self.clean(): return self.get_result()
417             else :
418                 if not self.prepare(): return self.get_result()
419                 if not self.cmake(): return self.get_result()
420                 if not self.make(): return self.get_result()
421                 if not self.install(): return self.get_result()
422                 if not self.clean(): return self.get_result()
423
424         return self.get_result()
425
426     ##
427     # Performs a build with a script.
428     def do_python_script_build(self, script, nb_proc):
429         # script found
430         self.logger.write(_("Compile %(product)s using script %(script)s\n") % \
431             { 'product': self.product_info.name,
432              'script': src.printcolors.printcLabel(script) }, 4)
433         try:
434             import imp
435             product = self.product_info.name
436             pymodule = imp.load_source(product + "_compile_script", script)
437             self.nb_proc = nb_proc
438             retcode = pymodule.compil(self.config, self, self.logger)
439         except:
440             __, exceptionValue, exceptionTraceback = sys.exc_info()
441             self.logger.write(str(exceptionValue), 1)
442             import traceback
443             traceback.print_tb(exceptionTraceback)
444             traceback.print_exc()
445             retcode = 1
446         finally:
447             self.put_txt_log_in_appli_log_dir("script")
448
449         return retcode
450
451     def complete_environment(self, make_options):
452         assert self.build_environ is not None
453         # pass additional variables to environment 
454         # (may be used by the build script)
455         self.build_environ.set("APPLICATION_NAME", self.config.APPLICATION.name)
456         self.build_environ.set("SOURCE_DIR", str(self.source_dir))
457         self.build_environ.set("INSTALL_DIR", str(self.install_dir))
458         self.build_environ.set("PRODUCT_INSTALL", str(self.install_dir))
459         self.build_environ.set("BUILD_DIR", str(self.build_dir))
460         self.build_environ.set("PRODUCT_BUILD", str(self.build_dir))
461         self.build_environ.set("MAKE_OPTIONS", make_options)
462         self.build_environ.set("DIST_NAME", self.config.VARS.dist_name)
463         self.build_environ.set("DIST_VERSION", self.config.VARS.dist_version)
464         self.build_environ.set("DIST", self.config.VARS.dist)
465         self.build_environ.set("VERSION", self.product_info.version)
466         # if product is in hpc mode, set SAT_HPC to 1 
467         # in order for the compilation script to take it into account
468         if src.product.product_is_hpc(self.product_info):
469             self.build_environ.set("SAT_HPC", "1")
470
471     def do_batch_script_build(self, script, nb_proc):
472
473         if src.architecture.is_windows():
474             make_options = "/maxcpucount:%s" % nb_proc
475         else :
476             make_options = "-j%s" % nb_proc
477
478         self.log_command("  " + _("Run build script %s\n") % script)
479         self.complete_environment(make_options)
480         
481         res = subprocess.call(script, 
482                               shell=True,
483                               stdout=self.logger.logTxtFile,
484                               stderr=subprocess.STDOUT,
485                               cwd=str(self.build_dir),
486                               env=self.build_environ.environ.environ)
487
488         res_check=self.check_install()
489         if res_check > 0 :
490             self.log_command("Error in sat check install - some files are not installed!")
491
492         self.put_txt_log_in_appli_log_dir("script")
493         res += res_check
494         if res == 0:
495             return res
496         else:
497             return 1
498     
499     def do_script_build(self, script, number_of_proc=0):
500         # define make options (may not be used by the script)
501         if number_of_proc==0:
502             nb_proc = src.get_cfg_param(self.product_info,"nb_proc", 0)
503             if nb_proc == 0: 
504                 nb_proc = self.config.VARS.nb_proc
505         else:
506             nb_proc = min(number_of_proc, self.config.VARS.nb_proc)
507             
508         extension = script.split('.')[-1]
509         if extension in ["bat","sh"]:
510             return self.do_batch_script_build(script, nb_proc)
511         if extension == "py":
512             return self.do_python_script_build(script, nb_proc)
513         
514         msg = _("The script %s must have .sh, .bat or .py extension." % script)
515         raise src.SatException(msg)
516     
517     def put_txt_log_in_appli_log_dir(self, file_name):
518         '''Put the txt log (that contain the system logs, like make command
519            output) in the directory <APPLICATION DIR>/LOGS/<product_name>/
520     
521         :param file_name Str: the name of the file to write
522         '''
523         if self.logger.logTxtFile == sys.__stdout__:
524             return
525         dir_where_to_put = os.path.join(self.config.APPLICATION.workdir,
526                                         "LOGS",
527                                         self.product_info.name)
528         file_path = os.path.join(dir_where_to_put, file_name)
529         src.ensure_path_exists(dir_where_to_put)
530         # write the logTxtFile copy it to the destination, and then recreate 
531         # it as it was
532         self.logger.logTxtFile.close()
533         shutil.move(self.logger.txtFilePath, file_path)
534         self.logger.logTxtFile = open(str(self.logger.txtFilePath), 'w')
535         self.logger.logTxtFile.write(open(file_path, "r").read())
536