]> SALOME platform Git repositories - modules/kernel.git/blob - src/Container/SALOME_Container.py
Salome HOME
e58adf5650fb6e3491a83514b88cf8d461ee86f1
[modules/kernel.git] / src / Container / SALOME_Container.py
1 #  -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2023  CEA, EDF, 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, or (at your option) any later version.
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
24 #  SALOME Container : implementation of container and engine for Kernel
25 #  File   : SALOME_Container.py
26 #  Author : Paul RASCLE, EDF
27 #  Module : SALOME
28 #  $Header$
29
30 ## @package SALOME_Container
31 # \brief python implementation of container interface for Kernel
32 #
33
34 import os
35 import sys
36 import traceback
37 import importlib
38 from omniORB import CORBA, PortableServer
39 import SALOMEDS
40 import Engines, Engines__POA
41 from SALOME_NamingServicePy import *
42 from SALOME_ComponentPy import *
43 import SALOME_PyNode
44 from collections import defaultdict
45
46 from SALOME_utilities import *
47 from Utils_Identity import getShortHostName
48 from launchConfigureParser import verbose
49 from KernelBasis import VerbosityActivated
50
51 class ScriptExecInfo:
52     @classmethod
53     def GetRepresentationOfTimeDelta(cls,endTime, startTime):
54        if endTime is None and startTime is None:
55           return "not measured"
56        td = endTime - startTime
57        import time
58        ts_of_td = time.gmtime(td.total_seconds())
59        return "{}.{:06d}".format(time.strftime("%H:%M:%S",ts_of_td),td.microseconds)
60
61     def __init__(self):
62       self._start_exec_time = None
63       self._end_exec_time = None
64       self._start_input_time = None
65       self._end_input_time = None
66       self._start_output_time = None
67       self._end_output_time = None
68
69     @property
70     def startInputTime(self):
71       return self._start_input_time
72     
73     @startInputTime.setter
74     def startInputTime(self,value):
75       self._start_input_time = value
76
77     @property
78     def endInputTime(self):
79       return self._end_input_time
80     
81     @endInputTime.setter
82     def endInputTime(self,value):
83       self._end_input_time = value
84
85     @property
86     def startExecTime(self):
87       return self._start_exec_time
88     
89     @startExecTime.setter
90     def startExecTime(self,value):
91       self._start_exec_time = value
92
93     @property
94     def endExecTime(self):
95       return self._end_exec_time
96     
97     @endExecTime.setter
98     def endExecTime(self,value):
99       self._end_exec_time = value
100
101     @property
102     def startOutputTime(self):
103       return self._start_output_time
104     
105     @startOutputTime.setter
106     def startOutputTime(self,value):
107       self._start_output_time = value
108
109     @property
110     def endOutputTime(self):
111       return self._end_output_time
112     
113     @endOutputTime.setter
114     def endOutputTime(self,value):
115       self._end_output_time = value
116
117     @property
118     def execTimeStr(self):
119        return ScriptExecInfo.GetRepresentationOfTimeDelta(self.endExecTime,self.startExecTime)
120     
121     @property
122     def inputTimeStr(self):
123        return ScriptExecInfo.GetRepresentationOfTimeDelta(self.endInputTime,self.startInputTime)
124
125     def __str__(self):
126       return """start exec time = {self.startExecTime}
127 end exec time = {self.endExecTime}
128 exec_time = {self.execTimeStr}
129 input unpickling and ev load from disk time = {self.inputTimeStr}
130 output serialization and ev write to disk time = {self.inputTimeStr}""".format(**locals())
131
132 class ScriptInfo:
133   def __init__(self, nodeName):
134       self._node_name = nodeName
135       self._code = ""
136       self._exec = defaultdict(ScriptExecInfo)
137
138   @property
139   def execs(self):
140       return self._exec
141
142   @property
143   def nodeName(self):
144       return self._node_name
145
146   @property
147   def code(self):
148       return self._code
149   
150   @code.setter
151   def code(self,value):
152       self._code = value
153
154   def __str__(self):
155       return """code = {self.code}\nexecs = {self.execs}""".format(**locals())
156   
157   def __repr__(self):
158       return """ScriptInfo \"{self.nodeName}\"""".format(**locals())
159
160 #=============================================================================
161
162 #define an implementation of the container interface for embedding in Container implemented in C++
163
164 class SALOME_Container_i:
165     _orb = None
166     _poa = None
167     _containerName = ""
168     _naming_service = None
169
170     #-------------------------------------------------------------------------
171
172     def __init__(self ,containerName, containerIORStr):
173         MESSAGE( "SALOME_Container_i::__init__" )
174         try:
175           argv = sys.argv
176         except AttributeError :
177           # for embedded python interpreter
178           # shouldn't be needed after python 3.8
179           # see https://bugs.python.org/issue32573
180           argv = ['']
181         self._orb = CORBA.ORB_init(argv, CORBA.ORB_ID)
182         self._poa = self._orb.resolve_initial_references("RootPOA")
183         self._containerName = containerName
184         self._dbg_info = []
185         if verbose(): print("SALOME_Container.SALOME_Container_i : _containerName ",self._containerName)
186         self._container = self._orb.string_to_object(containerIORStr)
187
188     #-------------------------------------------------------------------------
189
190     def import_component(self, componentName):
191         MESSAGE( "SALOME_Container_i::import_component" )
192         ret=""
193         try:
194             if verbose(): print("try import ",componentName)
195             importlib.import_module(componentName)
196             if verbose(): print("import ",componentName," successful")
197         except ImportError:
198             #can't import python module componentName
199             #try to find it in python path
200             try:
201               _specs = importlib.util.find_spec(componentName)
202               _module = importlib.util.module_from_spec(_specs)
203               _specs.loader.exec_module(_module)
204               #module file found in path
205               ret="Component "+componentName+": Python implementation found but it can't be loaded\n"
206               ret=ret+traceback.format_exc(10)
207             except ImportError as ee:
208               ret="ImplementationNotFound"
209             except Exception:
210               if verbose():print("error when calling find_module")
211               ret="ImplementationNotFound"
212         except Exception:
213             ret="Component "+componentName+": Python implementation found but it can't be loaded\n"
214             ret=ret+traceback.format_exc(10)
215             if verbose():
216               traceback.print_exc()
217               print("import ",componentName," not possible")
218         return ret
219
220     #-------------------------------------------------------------------------
221
222     def create_component_instance(self, componentName, instanceName):
223         MESSAGE( "SALOME_Container_i::create_component_instance" )
224         comp_iors=""
225         ret=""
226         try:
227             component=importlib.import_module(componentName)
228             factory=getattr(component,componentName)
229             comp_i=factory(self._orb,
230                            self._poa,
231                            self._container,
232                            self._containerName,
233                            instanceName,
234                            componentName)
235
236             MESSAGE( "SALOME_Container_i::create_component_instance : OK")
237             comp_o = comp_i._this()
238             comp_iors = self._orb.object_to_string(comp_o)
239         except Exception:
240             ret=traceback.format_exc(10)
241             traceback.print_exc()
242             MESSAGE( "SALOME_Container_i::create_component_instance : NOT OK")
243         return comp_iors, ret
244
245
246     def create_pynode(self,nodeName,code):
247         try:
248           node=SALOME_PyNode.PyNode_i(nodeName,code,self._poa,self)
249           id_o = self._poa.activate_object(node)
250           comp_o = self._poa.id_to_reference(id_o)
251           comp_iors = self._orb.object_to_string(comp_o)
252           return 0,comp_iors
253         except Exception:
254           exc_typ,exc_val,exc_fr=sys.exc_info()
255           l=traceback.format_exception(exc_typ,exc_val,exc_fr)
256           return 1,"".join(l)
257
258     def create_pyscriptnode(self,nodeName,code):
259         import pickle
260         try:
261           self._dbg_info.append( ScriptInfo(nodeName) )
262           node=SALOME_PyNode.PyScriptNode_i(nodeName,code,self._poa,self)
263           node.setIDInContainer(len(self._dbg_info)-1)
264           self.addInfoOnLevel1(node.getIDInContainer(),"code",code)
265           id_o = self._poa.activate_object(node)
266           comp_o = self._poa.id_to_reference(id_o)
267           comp_iors = self._orb.object_to_string(comp_o)
268           return 0,comp_iors
269         except Exception:
270           exc_typ,exc_val,exc_fr=sys.exc_info()
271           l=traceback.format_exception(exc_typ,exc_val,exc_fr)
272           return 1,"".join(l)
273         
274     def positionVerbosityOfLogger(self):
275         if VerbosityActivated():
276           import salome_utils
277           salome_utils.positionVerbosityOfLoggerRegardingState()
278
279     def addInfoOnLevel1(self, pos, key, value):
280         setattr(self._dbg_info[pos],key,value)
281         
282     def addInfoOnLevel2(self, pos0, pos1, key, value):
283         setattr(self._dbg_info[pos0].execs[pos1],key,value)
284         
285     def addTimeInfoOnLevel2(self, pos0, pos1, key):
286         from datetime import datetime
287         self.addInfoOnLevel2(pos0, pos1, key,datetime.now())
288
289     def getAllInfo(self):
290         import pickle
291         return pickle.dumps( self._dbg_info )