Salome HOME
Porting to Python 2.6 - add coding page specification for Python scripts
[modules/kernel.git] / src / Container / SALOME_ContainerPy.py
1 #! /usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 #  Copyright (C) 2007-2008  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.
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 #  SALOME Container : implementation of container and engine for Kernel
25 #  File   : SALOME_ContainerPy.py
26 #  Author : Paul RASCLE, EDF
27 #  Module : SALOME
28 #  $Header$
29 #
30 import os
31 import sys
32 import string
33
34 from omniORB import CORBA, PortableServer
35 import SALOMEDS 
36 import Engines, Engines__POA
37 from SALOME_NamingServicePy import *
38 from SALOME_ComponentPy import *
39
40 from SALOME_utilities import *
41 from Utils_Identity import getShortHostName
42 from launchConfigureParser import verbose
43
44 #=============================================================================
45
46 #define an implementation of the container interface for the container implemented in Python
47
48 class SALOME_ContainerPy_i (Engines__POA.Container):
49     _orb = None
50     _poa = None
51     _numInstance = 0
52     _listInstances_map = {}
53
54     #-------------------------------------------------------------------------
55
56     def __init__(self, orb, poa, containerName):
57         MESSAGE( "SALOME_ContainerPy_i::__init__" )
58         self._orb = orb
59         self._poa = poa
60         myMachine=getShortHostName()
61         Container_path = "/Containers/" + myMachine + "/" + 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             import traceback
178             traceback.print_exc()
179             print "import ",componentName," not possible"
180         return ret
181
182     #-------------------------------------------------------------------------
183
184     def load_component_Library(self, componentName):
185         MESSAGE(  "SALOME_ContainerPy_i::load_component_Library " + str(componentName) )
186         ret = 0
187         instanceName = componentName + "_inst_" + `self._numInstance`
188         interfaceName = componentName
189         return self.import_component(componentName)
190     
191     #-------------------------------------------------------------------------
192
193     def create_component_instance(self, componentName, studyId):
194         MESSAGE( "SALOME_ContainerPy_i::create_component_instance ==> " + str(componentName) + ' ' + str(studyId) )
195         if studyId < 0:
196             MESSAGE( "Study ID is lower than 0!" )
197             return None
198         else:
199             self._numInstance = self._numInstance +1
200             instanceName = componentName + "_inst_" + `self._numInstance`
201             comp_iors=""
202             try:
203                 component=__import__(componentName)
204                 factory=getattr(component,componentName)
205                 comp_i=factory(self._orb,
206                                self._poa,
207                                self._this(),
208                                self._containerName,
209                                instanceName,
210                                componentName)
211                 
212                 MESSAGE( "SALOME_Container_i::create_component_instance : OK")
213                 comp_o = comp_i._this()
214                 self._listInstances_map[instanceName] = comp_i
215             except:
216                 import traceback
217                 traceback.print_exc()
218                 MESSAGE( "SALOME_Container_i::create_component_instance : NOT OK")
219             return comp_o
220
221     #-------------------------------------------------------------------------
222
223     def find_component_instance(self, registeredName, studyId):
224         anEngine = None
225         keysList = self._listInstances_map.keys()
226         i = 0
227         while i < len(keysList):
228             instance = keysList[i]
229             if find(instance,registeredName) == 0:
230                 anEngine = self._listInstances_map[instance]
231                 if studyId == anEngine.getStudyId():
232                     return anEngine._this()
233             i = i + 1
234         return anEngine._this()
235         
236         
237     #-------------------------------------------------------------------------
238
239     def remove_impl(self, component):
240         MESSAGE( "SALOME_ContainerPy_i::remove_impl" )
241         instanceName = component._get_instanceName()
242         MESSAGE( "unload component " + str(instanceName) )
243         self._listInstances_map.remove(instanceName)
244         component.destroy()
245         self._naming_service.Destroy_Name(str(instanceName))
246
247     #-------------------------------------------------------------------------
248
249     def finalize_removal(self):
250         MESSAGE( "SALOME_ContainerPy_i::finalize_removal" )
251         return None
252
253     #-------------------------------------------------------------------------
254
255     def ping(self):
256         MESSAGE( "SALOME_ContainerPy_i::ping() pid " + str(os.getpid()) )
257         return None
258
259     #-------------------------------------------------------------------------
260
261     def getPID(self):
262         return os.getpid()
263
264     #-------------------------------------------------------------------------
265
266     def _get_name(self):
267         MESSAGE( "SALOME_ContainerPy_i::_get_name" )
268         return self._containerName
269
270     #-------------------------------------------------------------------------
271
272     def getHostName(self):
273         MESSAGE( "SALOME_ContainerPy_i::_get_MachineName" )
274         self._machineName = "localhost"
275         return self._machineName
276
277     #-------------------------------------------------------------------------
278     
279     def _get_machineName(self):
280         MESSAGE( "SALOME_ContainerPy_i::_get_MachineName" )
281         self._machineName = "localhost"
282         return self._machineName
283
284     #-------------------------------------------------------------------------
285
286     def Shutdown(self):
287         self._naming_service.Destroy_Name(self._containerName);
288         self._naming_service.Destroy_FullDirectory(self._containerName);
289         self._orb.shutdown(0)
290         pass
291
292     def _get_logfilename(self):
293       return self._logfilename
294     def _set_logfilename(self,logfilename):
295       self._logfilename=logfilename
296     def _get_workingdir(self):
297       return os.getcwd()
298
299 #=============================================================================
300
301 if __name__ == "__main__":
302   # change the stdout buffering to line buffering (same as C++ cout buffering)
303   sys.stdout=os.fdopen(1,"w",1)
304   #initialise the ORB and find the root POA
305   if verbose():print "Starting ",sys.argv[1]
306   orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
307   poa = orb.resolve_initial_references("RootPOA")
308   if verbose():print "ORB and POA initialized"
309
310   #create an instance of SALOME_ContainerPy_i and a Container reference
311   #containerName = "FactoryServerPy"
312   MESSAGE( str(sys.argv) )
313   containerName = sys.argv[1]
314   cpy_i = SALOME_ContainerPy_i(orb, poa, containerName)
315   if verbose():print "SALOME_ContainerPy_i instance created ",cpy_i 
316   cpy_o = cpy_i._this()
317   if verbose():print "SALOME_ContainerPy_i instance activated ",cpy_o
318   sys.stdout.flush()
319   sys.stderr.flush()
320
321   #activate the POA
322   poaManager = poa._get_the_POAManager()
323   poaManager.activate()
324
325   #Block for ever
326   orb.run()
327   if verbose():print "SALOME_ContainerPy_i shutdown"