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