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