]> SALOME platform Git repositories - modules/kernel.git/blob - bin/runSalomeCommon.py
Salome HOME
[EDF29150] : log performance of python scripts run inside SALOME container + verbosit...
[modules/kernel.git] / bin / runSalomeCommon.py
1 #!/usr/bin/env python3
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2023  CEA, EDF, OPEN CASCADE
4 #
5 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
7 #
8 # This library is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License, or (at your option) any later version.
12 #
13 # This library is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 # Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with this library; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
21 #
22 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 #
24
25 ## @package runSalome
26 # \brief Module that provides services to launch SALOME
27 #
28
29 import sys, os, string, glob, time, pickle, re
30 import setenv
31 from server import process_id, Server
32 import json
33 import subprocess
34 from salomeContextUtils import ScriptAndArgsObjectEncoder
35 import platform
36 import logging
37 from salome_utils import positionVerbosityOfLogger
38
39 logger = logging.getLogger()
40
41 def setVerbose(verbose):
42     verbose_map = { "0": logging.WARNING, "1": logging.INFO, "2": logging.DEBUG}
43     positionVerbosityOfLogger( verbose_map[verbose] )
44 # -----------------------------------------------------------------------------
45 #
46 # Class definitions to launch CORBA Servers
47 #
48
49 class InterpServer(Server):
50     def __init__(self,args):
51         self.args=args
52         if sys.platform == "win32":
53           self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
54         elif sys.platform == "darwin":
55           env_ld_library_path=['env', 'DYLD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
56           self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
57         else:
58           env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
59           self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
60
61     def run(self):
62         global process_id
63         command = self.CMD
64         print("INTERPSERVER::command = ", command)
65         import subprocess
66         pid = subprocess.Popen(command).pid
67         process_id[pid]=self.CMD
68         self.PID = pid
69
70 # ---
71
72 def get_cata_path(list_modules,modules_root_dir):
73     """Build a list of catalog paths (cata_path) to initialize the ModuleCatalog server
74     """
75     modules_cata={}
76     cata_path=[]
77
78     for module in list_modules:
79         if module in modules_root_dir:
80             module_root_dir=modules_root_dir[module]
81             module_cata=module+"Catalog.xml"
82             cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
83
84             if os.path.exists(cata_file):
85                 cata_path.append(cata_file)
86                 modules_cata[module]=cata_file
87             else:
88                 cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources", module_cata)
89                 if os.path.exists(cata_file):
90                     cata_path.append(cata_file)
91                     modules_cata[module]=cata_file
92
93     for path in os.getenv("SALOME_CATALOGS_PATH","").split(os.pathsep):
94         if os.path.exists(path):
95             for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
96                 module_name= os.path.basename(cata_file)[:-11]
97                 if module_name not in modules_cata:
98                     cata_path.append(cata_file)
99                     modules_cata[module_name]=cata_file
100
101     return cata_path
102
103 class CatalogServer(Server):
104     def __init__(self,args):
105         self.args=args
106         self.initArgs()
107         self.SCMD1=['SALOME_ModuleCatalog_Server']
108         if 'launcher' in self.args:
109             pos = args['launcher'].find(":")
110             if pos != -1:
111               self.SCMD1+=['-ORBInitRef']
112               machine = args['launcher'][0:pos]
113               port = args['launcher'][pos+1:]
114               self.SCMD1+=["NameService=corbaname::" + machine + ":" + port]
115         self.SCMD1+=['-common']
116         self.SCMD2=[]
117         home_dir=os.path.expanduser("~")
118         if home_dir is not None:
119             self.SCMD2=['-personal',os.path.join(home_dir,'Salome', 'resources', 'CatalogModulePersonnel.xml')]
120
121     def setpath(self,modules_list,modules_root_dir):
122         list_modules = modules_list[:]
123         list_modules.reverse()
124         if self.args["gui"] :
125             list_modules = ["KERNEL", "GUI"] + list_modules
126         else :
127             list_modules = ["KERNEL"] + list_modules
128
129         cata_path=get_cata_path(list_modules,modules_root_dir)
130
131         self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
132
133 # ---
134
135 class SalomeDSServer(Server):
136     def __init__(self,args):
137         self.args=args
138         self.initArgs()
139         self.CMD=['SALOMEDS_Server']
140         if 'launcher' in self.args:
141             pos = args['launcher'].find(":")
142             if pos != -1:
143               self.CMD+=['-ORBInitRef']
144               machine = args['launcher'][0:pos]
145               port = args['launcher'][pos+1:]
146               self.CMD+=["NameService=corbaname::" + machine + ":" + port]
147
148 # ---
149
150 class ConnectionManagerServer(Server):
151     def __init__(self,args):
152         self.args=args
153         self.initArgs()
154         self.CMD=['SALOME_ConnectionManagerServer']
155         if 'launcher' in self.args:
156             pos = args['launcher'].find(":")
157             if pos != -1:
158               self.CMD+=['-ORBInitRef']
159               machine = args['launcher'][0:pos]
160               port = args['launcher'][pos+1:]
161               self.CMD+=["NameService=corbaname::" + machine + ":" + port]
162
163
164 # ---
165
166 class RegistryServer(Server):
167     def __init__(self,args):
168         self.args=args
169         self.initArgs()
170         self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
171         if 'launcher' in self.args:
172             pos = args['launcher'].find(":")
173             if pos != -1:
174               self.CMD+=['-ORBInitRef']
175               machine = args['launcher'][0:pos]
176               port = args['launcher'][pos+1:]
177               self.CMD+=["NameService=corbaname::" + machine + ":" + port]
178
179 # ---
180
181 class ContainerCPPServer(Server):
182     def __init__(self,args,with_gui=False):
183         self.args=args
184         self.initArgs()
185         self.CMD=['SALOME_Container']
186         if 'launcher' in self.args:
187             pos = args['launcher'].find(":")
188             if pos != -1:
189               self.CMD+=['-ORBInitRef']
190               machine = args['launcher'][0:pos]
191               port = args['launcher'][pos+1:]
192               self.CMD+=["NameService=corbaname::" + machine + ":" + port]
193         self.CMD+=['FactoryServer']
194         if not with_gui and self.args["valgrind_session"]:
195             l = ["valgrind"]
196             val = os.getenv("VALGRIND_OPTIONS")
197             if val:
198                 l += val.split()
199                 pass
200             self.CMD = l + self.CMD
201             pass
202
203 # ---
204
205 class LoggerServer(Server):
206     def __init__(self,args):
207         self.args=args
208         self.initArgs()
209         from salome_utils import generateFileName, getLogDir
210         logfile = generateFileName( getLogDir(),
211                                     prefix="logger",
212                                     extension="log",
213                                     with_username=True,
214                                     with_hostname=True,
215                                     with_port=True)
216         print("===========================================================")
217         print("Logger server: put log to the file:")
218         print(logfile)
219         print("===========================================================")
220         self.CMD=['SALOME_Logger_Server', logfile]
221         pass
222     pass # end of LoggerServer class
223
224 # ---
225 import abc
226 import tempfile
227 class CommonSessionServer(Server):
228     def __init__(self,args,modules_list,modules_root_dir):
229         self.args = args.copy()
230         # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
231         #self.args['xterm']=0
232         #
233         self.initArgs()
234         self.SCMD1=[self.getSessionServerExe()]
235         if "SQUISH_PREFIX" in os.environ:
236             if platform.system() == "Windows" :
237                 self.SCMD1 = [os.path.join(os.getenv("SQUISH_PREFIX"), "bin", "dllpreload.exe"),os.path.join(os.getenv("SQUISH_SALOME_PATH"), "W64", "GUI", "bin", "salome", self.SCMD1[0])]
238             else :
239                 os.environ["LD_LIBRARY_PATH"] = os.environ["SQUISH_PREFIX"] + "/lib:" + os.environ["LD_LIBRARY_PATH"]
240         self.SCMD2=[]
241         if 'launcher' in self.args:
242             pos = args['launcher'].find(":")
243             if pos != -1:
244               self.SCMD1+=['-ORBInitRef']
245               machine = args['launcher'][0:pos]
246               port = args['launcher'][pos+1:]
247               self.SCMD1+=["NameService=corbaname::" + machine + ":" + port]
248         if 'registry' in self.args['embedded']:
249             self.SCMD1+=['--with','Registry',
250                          '(','--salome_session','theSession',')']
251         if 'moduleCatalog' in self.args['embedded']:
252             self.SCMD1+=['--with','ModuleCatalog','(','-common']
253             home_dir=os.path.expanduser("~")
254             if home_dir is not None:
255                 self.SCMD2+=['-personal',os.path.join(home_dir,'Salome','resources','CatalogModulePersonnel.xml')]
256             self.SCMD2+=[')']
257         if 'study' in self.args['embedded']:
258             self.SCMD2+=['--with','SALOMEDS','(',')']
259         if 'cppContainer' in self.args['embedded']:
260             self.SCMD2+=['--with','Container','(','FactoryServer',')']
261         if 'SalomeAppEngine' in self.args['embedded']:
262             self.SCMD2+=['--with','SalomeAppEngine','(',')']
263
264         if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
265             self.SCMD2+=['CPP']
266         if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
267             raise Exception('Python containers no longer supported')
268         if self.args['gui']:
269             session_gui = self.args.get('session_gui', True)
270             if not session_gui:
271                 self.SCMD2+=['--hide-desktop']
272             else:
273                 if not self.args['splash']:
274                     self.SCMD2+=['--hide-splash']
275                     pass
276                 if self.args['study_hdf'] is not None:
277                     self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
278                     pass
279                 pass
280                 if 'pyscript' in self.args and len(self.args['pyscript']) > 0:
281                     msg = json.dumps(self.args['pyscript'], cls=ScriptAndArgsObjectEncoder)
282                     self.SCMD2+=['--pyscript=%s'%(msg)]
283                     pass
284                 pass
285                 if self.args['gui_log_file'] is not None:
286                     guilogfile = self.args['gui_log_file']
287                     if os.path.exists(guilogfile) and os.path.isfile(guilogfile):
288                         try:
289                             os.remove(guilogfile)
290                         except:
291                             print("Error: cannot remove existing log file", guilogfile)
292                             guilogfile = None
293                     if guilogfile is not None:
294                         self.SCMD2+=['--gui-log-file=%s'%guilogfile]
295                     pass
296                 pass
297             pass
298         if self.args['noexcepthandler']:
299             self.SCMD2+=['--no-exception-handler']
300         if 'user_config' in self.args:
301             self.SCMD2+=['--resources=%s'%self.args['user_config']]
302         if 'modules' in self.args:
303             list_modules = []
304             #keep only modules with GUI
305             for m in modules_list:
306               if m not in modules_root_dir:
307                 list_modules.insert(0,m)
308               else:
309                 fr1 = os.path.join(modules_root_dir[m],"share","salome","resources",m.lower(),"SalomeApp.xml")
310                 fr2 = os.path.join(modules_root_dir[m],"share","salome","resources","SalomeApp.xml")
311                 if os.path.exists(fr1) or os.path.exists(fr2):
312                   list_modules.insert(0,m)
313             list_modules.reverse()
314             self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
315             pass
316         if 'language' in self.args:
317             self.SCMD2+=['--language=%s' % self.args['language']]
318         os_handle, iorfakens = tempfile.mkstemp()
319         self.iorfakens = iorfakens
320         os.close(os_handle)
321         self.SCMD2+=["--iorfakens={}".format(iorfakens)]
322         pass
323
324     @abc.abstractmethod
325     def getSessionServerExe(self):
326         pass
327     
328     def setpath(self,modules_list,modules_root_dir):
329         list_modules = modules_list[:]
330         list_modules.reverse()
331         if self.args["gui"] :
332             list_modules = ["KERNEL", "GUI"] + list_modules
333         else :
334             list_modules = ["KERNEL"] + list_modules
335
336         cata_path=get_cata_path(list_modules,modules_root_dir)
337
338         if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
339             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
340             self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
341         else:
342             self.CMD=self.SCMD1 + self.SCMD2
343         if 'test' in self.args:
344             self.CMD+=['-test'] + self.args['test']
345         elif 'play' in self.args:
346             self.CMD+=['-play'] + self.args['play']
347
348         if self.args["gdb_session"] or self.args["ddd_session"]:
349             f = open(".gdbinit4salome", "w")
350             f.write("set args ")
351             args = " ".join(self.CMD[1:])
352             args = args.replace("(", "\(")
353             args = args.replace(")", "\)")
354             f.write(args)
355             f.write("\n")
356             f.close()
357             if self.args["ddd_session"]:
358                 self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
359             elif self.args["gdb_session"]:
360                 self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
361                 pass
362             pass
363
364         if self.args["valgrind_session"]:
365             l = ["valgrind"]
366             val = os.getenv("VALGRIND_OPTIONS")
367             if val:
368                 l += val.split()
369                 pass
370             self.CMD = l + self.CMD
371             pass
372
373 class SessionServer(CommonSessionServer):
374     def __init__(self,args,modules_list,modules_root_dir):
375         super().__init__(args,modules_list,modules_root_dir)
376         import KernelBasis
377         KernelBasis.setSSLMode(False)
378     
379     def getSessionServerExe(self):
380         return "SALOME_Session_Server"
381 # ---
382
383 class LauncherServer(Server):
384     def __init__(self,args):
385         self.args=args
386         self.initArgs()
387         self.SCMD1=['SALOME_LauncherServer']
388         self.SCMD2=[]
389         if args["gui"] :
390             if 'registry' in self.args['embedded']:
391                 self.SCMD1+=['--with','Registry',
392                              '(','--salome_session','theSession',')']
393             if 'moduleCatalog' in self.args['embedded']:
394                 self.SCMD1+=['--with','ModuleCatalog','(','-common']
395                 home_dir=os.path.expanduser("~")
396                 if home_dir is not None:
397                     self.SCMD2=['-personal',os.path.join(home_dir,'Salome','resources','CatalogModulePersonnel.xml')]
398                 self.SCMD2+=[')']
399             if 'study' in self.args['embedded']:
400                 self.SCMD2+=['--with','SALOMEDS','(',')']
401             if 'cppContainer' in self.args['embedded']:
402                 self.SCMD2+=['--with','Container','(','FactoryServer',')']
403
404     def setpath(self,modules_list,modules_root_dir):
405         list_modules = modules_list[:]
406         list_modules.reverse()
407         if self.args["gui"] :
408             list_modules = ["KERNEL", "GUI"] + list_modules
409         else :
410             list_modules = ["KERNEL"] + list_modules
411
412         cata_path=get_cata_path(list_modules,modules_root_dir)
413
414         if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
415             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
416             self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
417         else:
418             self.CMD=self.SCMD1 + self.SCMD2