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