]> SALOME platform Git repositories - modules/kernel.git/blob - src/Container/SALOME_ContainerPy.py
Salome HOME
add options-help get from launcher
[modules/kernel.git] / src / Container / SALOME_ContainerPy.py
1 #! /usr/bin/env python3
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2024  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 #  SALOME Container : implementation of container and engine for Kernel
26 #  File   : SALOME_ContainerPy.py
27 #  Author : Paul RASCLE, EDF
28 #  Module : SALOME
29 #  $Header$
30 #
31 import os
32 import sys
33 import importlib
34
35 from omniORB import CORBA, PortableServer
36 import SALOMEDS
37 import Engines, Engines__POA
38 import salome_psutil
39 from SALOME_NamingServicePy import *
40 from SALOME_Embedded_NamingService import SALOME_Embedded_NamingService
41 from SALOME_ComponentPy import *
42
43 from SALOME_utilities import *
44 from Utils_Identity import getShortHostName
45 from launchConfigureParser import verbose
46
47 #=============================================================================
48
49 #define an implementation of the container interface for the container implemented in Python
50
51 class SALOME_ContainerPy_Gen_i(Engines__POA.Container):
52     """
53     Implementation without naming_service server
54     """
55     _orb = None
56     _poa = None
57     _numInstance = 0
58     _listInstances_map = {}
59     _script = ""
60
61     #-------------------------------------------------------------------------
62
63     def __init__(self, orb, poa, containerName):
64         MESSAGE( "SALOME_ContainerPy_i::__init__" )
65         self._orb = orb
66         self._poa = poa
67         self._load_script = None
68         myMachine=getShortHostName()
69         Container_path = "/Containers/" + myMachine + "/" + containerName
70         self._containerName = Container_path
71         if verbose(): print("container name ",self._containerName)
72
73     #-------------------------------------------------------------------------
74
75     def instance(self, nameToRegister, componentName):
76         MESSAGE(  "SALOME_ContainerPy_i::instance " + str(nameToRegister) + ' ' + str(componentName) )
77         self._numInstance = self._numInstance +1
78         instanceName = nameToRegister + "_inst_" + repr(self._numInstance)
79
80         component=importlib.import_module(componentName)
81         factory=getattr(component,componentName)
82         comp_i=factory(self._orb, self._poa, self._this(), self._containerName,
83                        instanceName, nameToRegister)
84
85         MESSAGE( "SALOME_ContainerPy_i::instance : component created")
86         comp_o = comp_i._this()
87         return comp_o
88
89     #-------------------------------------------------------------------------
90
91     def load_impl(self, nameToRegister, componentName):
92         MESSAGE(  "SALOME_ContainerPy_i::load_impl " + str(nameToRegister) + ' ' + str(componentName) )
93         self._numInstance = self._numInstance +1
94         instanceName = nameToRegister + "_inst_" + repr(self._numInstance)
95         interfaceName = nameToRegister
96         the_command = "import " + nameToRegister + "\n"
97         the_command = the_command + "comp_i = " + nameToRegister + "." + nameToRegister
98         the_command = the_command + "(self._orb, self._poa, self._this(), self._containerName, instanceName, interfaceName)\n"
99         MESSAGE( "SALOME_ContainerPy_i::load_impl :" + str (the_command) )
100         exec(the_command)
101         comp_o = comp_i._this()
102         return comp_o
103
104     #-------------------------------------------------------------------------
105
106     def import_component(self, componentName):
107         MESSAGE( "SALOME_Container_i::import_component" )
108         reason = ""
109         try:
110             if verbose(): print("try import %s" % componentName)
111             # try import component
112             module=importlib.import_module(componentName)
113             if verbose(): print("import %s is done successfully" % componentName)
114             # if import successfully, check that component is loadable
115             if not hasattr(module, componentName):
116                 reason = "module %s is not loadable" % componentName
117                 print(reason)
118                 pass
119             pass
120         except Exception:
121             import traceback
122             print("cannot import %s" % componentName)
123             traceback.print_exc()
124             reason = "cannot import %s" % componentName
125         return reason
126
127     #-------------------------------------------------------------------------
128
129     def load_component_Library(self, componentName):
130         MESSAGE(  "SALOME_ContainerPy_i::load_component_Library " + str(componentName) )
131         ret = 0
132         instanceName = componentName + "_inst_" + repr(self._numInstance)
133         interfaceName = componentName
134         reason = self.import_component(componentName)
135         return reason == "", reason
136
137     #-------------------------------------------------------------------------
138
139     def create_component_instance_env(self, componentName, env):
140       return self.create_component_instance(componentName), ""
141
142     def create_component_instance(self, componentName):
143         MESSAGE( "SALOME_ContainerPy_i::create_component_instance ==> " + str(componentName) )
144         self._numInstance = self._numInstance +1
145         instanceName = componentName + "_inst_" + repr(self._numInstance)
146         comp_iors=""
147         try:
148             component=importlib.import_module(componentName)
149             factory=getattr(component,componentName)
150             comp_i=factory(self._orb,
151                            self._poa,
152                            self._this(),
153                            self._containerName,
154                            instanceName,
155                            componentName)
156
157             MESSAGE( "SALOME_Container_i::create_component_instance : OK")
158             comp_o = comp_i._this()
159             self._listInstances_map[instanceName] = comp_i
160         except Exception:
161             import traceback
162             traceback.print_exc()
163             MESSAGE( "SALOME_Container_i::create_component_instance : NOT OK")
164         return comp_o
165
166     #-------------------------------------------------------------------------
167
168     def find_component_instance(self, registeredName):
169         anEngine = None
170         for instance in self._listInstances_map:
171             if find(instance,registeredName) == 0:
172                 anEngine = self._listInstances_map[instance]
173                 return anEngine._this()
174         return anEngine
175
176
177     #-------------------------------------------------------------------------
178
179     def create_python_service_instance(self, CompName):
180         return self.create_component_instance(CompName)
181
182     #-------------------------------------------------------------------------
183
184     def remove_impl(self, component):
185         MESSAGE( "SALOME_ContainerPy_i::remove_impl" )
186         instanceName = component._get_instanceName()
187         MESSAGE( "unload component " + str(instanceName) )
188         self._listInstances_map.remove(instanceName)
189         component.destroy()
190         self._naming_service.Destroy_Name(str(instanceName))
191
192     #-------------------------------------------------------------------------
193
194     def finalize_removal(self):
195         MESSAGE( "SALOME_ContainerPy_i::finalize_removal" )
196         return None
197
198     #-------------------------------------------------------------------------
199
200     def ping(self):
201         MESSAGE( "SALOME_ContainerPy_i::ping() pid " + str(os.getpid()) )
202         return None
203
204     #-------------------------------------------------------------------------
205
206     def getPID(self):
207         return os.getpid()
208
209     #-------------------------------------------------------------------------
210
211     def getNumberOfCPUCores(self):
212         return salome_psutil.getNumberOfCPUCores()
213
214     #-------------------------------------------------------------------------
215
216     def loadOfCPUCores(self):
217         return salome_psutil.loadOfCPUCores(self._load_script)
218
219     #-------------------------------------------------------------------------
220
221     def setPyScriptForCPULoad(self, script):
222         self._load_script = script
223
224     #-------------------------------------------------------------------------
225
226     def resetScriptForCPULoad(self):
227         self._load_script = None
228
229     #-------------------------------------------------------------------------
230
231     def getTotalPhysicalMemory(self):
232         return salome_psutil.getTotalPhysicalMemory()
233
234     #-------------------------------------------------------------------------
235
236     def getTotalPhysicalMemoryInUse(self):
237         return salome_psutil.getTotalPhysicalMemoryInUse()
238
239     #-------------------------------------------------------------------------
240
241     def getTotalPhysicalMemoryInUseByMe(self):
242         return salome_psutil.getTotalPhysicalMemoryInUseByMe()
243
244     #-------------------------------------------------------------------------
245
246     def _get_name(self):
247         MESSAGE( "SALOME_ContainerPy_i::_get_name" )
248         return self._containerName
249
250     #-------------------------------------------------------------------------
251
252     def getHostName(self):
253         MESSAGE( "SALOME_ContainerPy_i::_get_MachineName" )
254         self._machineName = "localhost"
255         return self._machineName
256
257     #-------------------------------------------------------------------------
258
259     def _get_machineName(self):
260         MESSAGE( "SALOME_ContainerPy_i::_get_MachineName" )
261         self._machineName = "localhost"
262         return self._machineName
263
264     #-------------------------------------------------------------------------
265
266     def Shutdown(self):
267         self._naming_service.Destroy_Name(self._containerName);
268         self._naming_service.Destroy_FullDirectory(self._containerName);
269         self._orb.shutdown(0)
270         pass
271
272     def _get_logfilename(self):
273       return self._logfilename
274     def _set_logfilename(self,logfilename):
275       self._logfilename=logfilename
276     def _get_workingdir(self):
277       return os.getcwd()
278
279 #=============================================================================
280
281 class SALOME_ContainerPy_i(SALOME_ContainerPy_Gen_i):
282     """
283     Implementation with naming_service server
284     """
285     def __init__(self, orb, poa, containerName):
286         SALOME_ContainerPy_Gen_i.__init__(self, orb, poa, containerName)
287         naming_service = SALOME_NamingServicePy_i(self._orb)
288         self._naming_service = naming_service
289         MESSAGE( str(Container_path) )
290         naming_service.Register(self._this(), Container_path)
291
292     #-------------------------------------------------------------------------
293
294     def start_impl(self, ContainerName):
295         MESSAGE(  "SALOME_ContainerPy_i::start_impl " + str(ContainerName) )
296         myMachine=getShortHostName()
297         theContainer = "/Containers/" + myMachine + "/" + ContainerName
298         try:
299             obj = self._naming_service.Resolve(theContainer)
300         except :
301             obj = None
302             MESSAGE(  "SALOME_ContainerPy_i::start_impl " + str(ContainerName) + ".object not found in Naming Service" )
303         if obj is None:
304             container = None
305         else:
306             container = obj._narrow(Engines.Container)
307             if container is None:
308                 MESSAGE( "SALOME_ContainerPy_i::start_impl " + str(containerName) + ".object exists but is not a Container" )
309             else :
310                 MESSAGE( "SALOME_ContainerPy_i::start_impl " + str(ContainerName) + ".object found without new launch" )
311             return container
312         #shstr = os.getenv( "PWD" ) + "/"
313         #shstr += "runSession ./SALOME_ContainerPy.py "
314         shstr = os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/SALOME_ContainerPy.py ";
315         #shstr = "runSession SALOME_ContainerPy.py "
316         shstr += ContainerName
317
318         # mpv: fix for SAL4731 - always create new file to write log of server
319         num = 1
320         fileName = ""
321         while 1:
322             fileName = "/tmp/"+ContainerName+"_%i.log"%num
323             if not os.path.exists(fileName):
324                 break
325             num += 1
326             pass
327
328         shstr += " > "
329         shstr += fileName
330         shstr += " 2>&1 &"
331
332         #shstr += " > /tmp/"
333         #shstr += ContainerName
334         #shstr += ".log 2>&1 &"
335
336         MESSAGE(  "SALOME_ContainerPy_i::start_impl " + "os.system(" + str(shstr) + ")" )
337         os.system( shstr )
338         count = 21
339         while container is None :
340             time.sleep(1)
341             count = count - 1
342             MESSAGE(  str(count) + ". Waiting for " + str(theContainer) )
343             try :
344                 obj = self._naming_service.Resolve(theContainer)
345             except :
346                 obj = None
347             if obj is None:
348                 container = None
349             else:
350                 container = obj._narrow(Engines.Container)
351                 if container is None:
352                     MESSAGE(  str(containerName) + ".object exists but is not a Container" )
353                 return container
354             if count == 0 :
355                 return container
356
357     pass
358
359 class SALOME_ContainerPy_SSL_i(SALOME_ContainerPy_Gen_i):
360     """
361     Implementation with naming_service server
362     """
363     def __init__(self, orb, poa, containerName):
364         SALOME_ContainerPy_Gen_i.__init__(self, orb, poa, containerName)
365         naming_service = SALOME_Embedded_NamingService()
366         self._naming_service = naming_service._this()
367
368     def get_embedded_NS_if_ssl(self):
369         return self._naming_service
370
371 if __name__ == "__main__":
372   # change the stdout buffering to line buffering (same as C++ cout buffering)
373   sys.stdout=os.fdopen(1,"w",1)
374   #initialise the ORB and find the root POA
375   if verbose():print("Starting ",sys.argv[1])
376   orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
377   poa = orb.resolve_initial_references("RootPOA")
378   if verbose():print("ORB and POA initialized")
379
380   #create an instance of SALOME_ContainerPy_i and a Container reference
381   #containerName = "FactoryServerPy"
382   MESSAGE( str(sys.argv) )
383   containerName = sys.argv[1]
384   cpy_i = SALOME_ContainerPy_i(orb, poa, containerName)
385   if verbose():print("SALOME_ContainerPy_i instance created ",cpy_i)
386   cpy_o = cpy_i._this()
387   if verbose():print("SALOME_ContainerPy_i instance activated ",cpy_o)
388   sys.stdout.flush()
389   sys.stderr.flush()
390
391   #activate the POA
392   poaManager = poa._get_the_POAManager()
393   poaManager.activate()
394
395   #Block for ever
396   orb.run()
397   if verbose():print("SALOME_ContainerPy_i shutdown")