Salome HOME
merge from branch BR_V5_DEV
[modules/yacs.git] / src / Container / SALOME_ContainerPy.py
1 #! /usr/bin/env python
2 #  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
3 #
4 #  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
5 #  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 #
7 #  This library is free software; you can redistribute it and/or
8 #  modify it under the terms of the GNU Lesser General Public
9 #  License as published by the Free Software Foundation; either
10 #  version 2.1 of the License.
11 #
12 #  This library is distributed in the hope that it will be useful,
13 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 #  Lesser General Public License for more details.
16 #
17 #  You should have received a copy of the GNU Lesser General Public
18 #  License along with this library; if not, write to the Free Software
19 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20 #
21 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 #
23 #  SALOME Container : implementation of container and engine for Kernel
24 #  File   : SALOME_ContainerPy.py
25 #  Author : Paul RASCLE, EDF
26 #  Module : SALOME
27 #  $Header$
28 #
29 import os
30 import sys
31 import string
32
33 from omniORB import CORBA, PortableServer
34 import SALOMEDS 
35 import Engines, Engines__POA
36 from SALOME_NamingServicePy import *
37 from SALOME_ComponentPy import *
38
39 from SALOME_utilities import *
40 from Utils_Identity import getShortHostName
41 from launchConfigureParser import verbose
42
43 #=============================================================================
44
45 #define an implementation of the container interface
46
47 class SALOME_ContainerPy_i (Engines__POA.Container):
48     _orb = None
49     _poa = None
50     _numInstance = 0
51     _listInstances_map = {}
52
53     #-------------------------------------------------------------------------
54
55     def __init__(self, orb, poa, containerName):
56         MESSAGE( "SALOME_ContainerPy_i::__init__" )
57         self._orb = orb
58         self._poa = poa
59         myMachine=getShortHostName()
60         Container_path = "/Containers/" + myMachine + "/" + containerName
61         #self._containerName = containerName
62         self._containerName = Container_path
63         if verbose(): print "container name ",self._containerName
64
65         naming_service = SALOME_NamingServicePy_i(self._orb)
66         self._naming_service = naming_service
67         MESSAGE( str(Container_path) )
68         naming_service.Register(self._this(), Container_path)
69             
70     #-------------------------------------------------------------------------
71
72     def start_impl(self, ContainerName):
73         MESSAGE(  "SALOME_ContainerPy_i::start_impl " + str(ContainerName) )
74         myMachine=getShortHostName()
75         theContainer = "/Containers/" + myMachine + "/" + ContainerName
76         try:
77             obj = self._naming_service.Resolve(theContainer)
78         except :
79             obj = None
80             MESSAGE(  "SALOME_ContainerPy_i::start_impl " + str(ContainerName) + ".object not found in Naming Service" )
81         if obj is None:
82             container = None
83         else:
84             container = obj._narrow(Engines.Container)
85             if container is None:
86                 MESSAGE( "SALOME_ContainerPy_i::start_impl " + str(containerName) + ".object exists but is not a Container" )
87             else :
88                 MESSAGE( "SALOME_ContainerPy_i::start_impl " + str(ContainerName) + ".object found without new launch" )
89             return container
90         #shstr = os.getenv( "PWD" ) + "/"
91         #shstr += "runSession ./SALOME_ContainerPy.py "
92         shstr = os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/SALOME_ContainerPy.py ";
93         #shstr = "runSession SALOME_ContainerPy.py "
94         shstr += ContainerName
95
96         # mpv: fix for SAL4731 - allways create new file to write log of server
97         num = 1
98         fileName = ""
99         while 1:
100             fileName = "/tmp/"+ContainerName+"_%i.log"%num
101             if not os.path.exists(fileName):
102                 break
103             num += 1
104             pass
105         
106         shstr += " > "
107         shstr += fileName
108         shstr += " 2>&1 &"
109         
110         #shstr += " > /tmp/"
111         #shstr += ContainerName
112         #shstr += ".log 2>&1 &"
113         
114         MESSAGE(  "SALOME_ContainerPy_i::start_impl " + "os.system(" + str(shstr) + ")" )
115         os.system( shstr )
116         count = 21
117         while container is None :
118             time.sleep(1)
119             count = count - 1
120             MESSAGE(  str(count) + ". Waiting for " + str(theContainer) )
121             try :
122                 obj = self._naming_service.Resolve(theContainer)
123             except :
124                 obj = None
125             if obj is None:
126                 container = None
127             else:
128                 container = obj._narrow(Engines.Container)
129                 if container is None:
130                     MESSAGE(  str(containerName) + ".object exists but is not a Container" )
131                 return container
132             if count == 0 :
133                 return container
134
135     #-------------------------------------------------------------------------
136
137     def instance(self, nameToRegister, componentName):
138         MESSAGE(  "SALOME_ContainerPy_i::instance " + str(nameToRegister) + ' ' + str(componentName) )
139         self._numInstance = self._numInstance +1
140         instanceName = nameToRegister + "_inst_" + `self._numInstance`
141
142         component=__import__(componentName)
143         factory=getattr(component,componentName)
144         comp_i=factory(self._orb, self._poa, self._this(), self._containerName,
145                        instanceName, nameToRegister)
146
147         MESSAGE( "SALOME_ContainerPy_i::instance : component created")
148         comp_o = comp_i._this()
149         return comp_o
150
151     #-------------------------------------------------------------------------
152
153     def load_impl(self, nameToRegister, componentName):
154         MESSAGE(  "SALOME_ContainerPy_i::load_impl " + str(nameToRegister) + ' ' + str(componentName) )
155         self._numInstance = self._numInstance +1
156         instanceName = nameToRegister + "_inst_" + `self._numInstance`
157         interfaceName = nameToRegister
158         the_command = "import " + nameToRegister + "\n"
159         the_command = the_command + "comp_i = " + nameToRegister + "." + nameToRegister
160         the_command = the_command + "(self._orb, self._poa, self._this(), self._containerName, instanceName, interfaceName)\n"
161         MESSAGE( "SALOME_ContainerPy_i::load_impl :" + str (the_command) )
162         exec the_command
163         comp_o = comp_i._this()
164         return comp_o
165     
166     #-------------------------------------------------------------------------
167     
168     def import_component(self, componentName):
169         MESSAGE( "SALOME_Container_i::import_component" )
170         ret=0
171         try:
172             if verbose(): print "try import ",componentName
173             module=__import__(componentName)
174             if verbose(): print "import ",componentName," successful"
175             ret=1
176         except:
177             if verbose(): 
178               import traceback
179               traceback.print_exc()
180               print "import ",componentName," not possible"
181         return ret
182
183     #-------------------------------------------------------------------------
184
185     def load_component_Library(self, componentName):
186         MESSAGE(  "SALOME_ContainerPy_i::load_component_Library " + str(componentName) )
187         ret = 0
188         instanceName = componentName + "_inst_" + `self._numInstance`
189         interfaceName = componentName
190         #the_command = "import " + componentName + "\n"
191         #the_command = the_command + "comp_i = " + componentName + "." + componentName
192         #the_command = the_command + "(self._orb, self._poa, self._this(), self._containerName, instanceName, interfaceName)\n"
193         #MESSAGE( "SALOME_ContainerPy_i::load_component_Library :" + str (the_command) )
194         #exec the_command
195         #comp_o = comp_i._this()
196         #if comp_o is not None:
197         #    ret = 1
198         #else:
199             # --- try to import Python component
200         #    retImpl = self.import_component(componentName)
201         #    if retImpl == 1:
202                 #import is possible
203         #        ret = 1
204         #    else:
205                 #import isn't possible
206         #        ret = 0
207         #return ret
208         return self.import_component(componentName)
209     
210     #-------------------------------------------------------------------------
211
212     def create_component_instance(self, componentName, studyId):
213         MESSAGE( "SALOME_ContainerPy_i::create_component_instance ==> " + str(componentName) + ' ' + str(studyId) )
214         if studyId < 0:
215             MESSAGE( "Study ID is lower than 0!" )
216             return None
217         else:
218             self._numInstance = self._numInstance +1
219             instanceName = componentName + "_inst_" + `self._numInstance`
220             comp_iors=""
221             try:
222                 component=__import__(componentName)
223                 factory=getattr(component,componentName)
224                 comp_i=factory(self._orb,
225                                self._poa,
226                                self._this(),
227                                self._containerName,
228                                instanceName,
229                                componentName)
230                 
231                 MESSAGE( "SALOME_Container_i::create_component_instance : OK")
232                 comp_o = comp_i._this()
233                 self._listInstances_map[instanceName] = comp_i
234             except:
235                 import traceback
236                 traceback.print_exc()
237                 MESSAGE( "SALOME_Container_i::create_component_instance : NOT OK")
238             return comp_o
239
240     #-------------------------------------------------------------------------
241
242     def find_component_instance(self, registeredName, studyId):
243         anEngine = None
244         keysList = self._listInstances_map.keys()
245         i = 0
246         while i < len(keysList):
247             instance = keysList[i]
248             if find(instance,registeredName) == 0:
249                 anEngine = self._listInstances_map[instance]
250                 if studyId == anEngine.getStudyId():
251                     return anEngine._this()
252             i = i + 1
253         return anEngine._this()
254         
255         
256     #-------------------------------------------------------------------------
257
258     def remove_impl(self, component):
259         MESSAGE( "SALOME_ContainerPy_i::remove_impl" )
260         instanceName = component._get_instanceName()
261         MESSAGE( "unload component " + str(instanceName) )
262         self._listInstances_map.remove(instanceName)
263         component.destroy()
264         self._naming_service.Destroy_Name(str(instanceName))
265
266     #-------------------------------------------------------------------------
267
268     def finalize_removal(self):
269         MESSAGE( "SALOME_ContainerPy_i::finalize_removal" )
270         return None
271
272     #-------------------------------------------------------------------------
273
274     def ping(self):
275         MESSAGE( "SALOME_ContainerPy_i::ping() pid " + str(os.getpid()) )
276         return None
277
278     #-------------------------------------------------------------------------
279
280     def getPID(self):
281         return os.getpid()
282
283     #-------------------------------------------------------------------------
284
285     def _get_name(self):
286         MESSAGE( "SALOME_ContainerPy_i::_get_name" )
287         return self._containerName
288
289     #-------------------------------------------------------------------------
290
291     def getHostName(self):
292         MESSAGE( "SALOME_ContainerPy_i::_get_MachineName" )
293         self._machineName = "localhost"
294         return self._machineName
295
296     #-------------------------------------------------------------------------
297     
298     def _get_machineName(self):
299         MESSAGE( "SALOME_ContainerPy_i::_get_MachineName" )
300         self._machineName = "localhost"
301         return self._machineName
302
303     #-------------------------------------------------------------------------
304
305     def Shutdown(self):
306         self._naming_service.Destroy_Name(self._containerName);
307         self._naming_service.Destroy_FullDirectory(self._containerName);
308         self._orb.shutdown(0)
309         pass
310
311     def _get_logfilename(self):
312       return self._logfilename
313     def _set_logfilename(self,logfilename):
314       self._logfilename=logfilename
315     def _get_workingdir(self):
316       return os.getcwd()
317
318 #=============================================================================
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"