Salome HOME
Updated copyright comment
[modules/yacs.git] / src / yacsorb / YACS.py
1 # Copyright (C) 2006-2024  CEA, EDF
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19
20 import sys
21 import YACS_ORB__POA
22 import YACS_ORB
23 import SALOME_ComponentPy
24 import SALOME_DriverPy
25
26 import threading
27 import tempfile
28 import os
29
30 import SALOMERuntime
31 import loader
32 import salomeloader
33 import pilot
34 import traceback
35
36 class proc_i(YACS_ORB__POA.ProcExec):
37     def __init__(self, xmlFile):
38         self.l = loader.YACSLoader()
39         self.e = pilot.ExecutorSwig()
40         self.e.setExecMode(1) # YACS::STEPBYSTEP
41         self.run1 = None
42         self.p = self.l.load(xmlFile)
43         self.xmlFile=xmlFile
44         pass
45
46     def getNodeState(self,numid):
47         return self.p.getNodeState(numid)
48
49     def getNodeProgress(self,numid):
50         return self.p.getNodeProgress(numid)
51
52     def getXMLState(self, numid):
53         return self.p.getXMLState(numid)
54
55     def getInPortValue(self, nodeNumid, portName):
56       try:
57         return self.p.getInPortValue(nodeNumid, portName)
58       except:
59         traceback.print_exc()
60         return ""
61
62     def setInPortValue(self, nodeName, portName, value):
63       try:
64         return self.p.setInPortValue(nodeName, portName, value)
65       except:
66         traceback.print_exc()
67         return ""
68
69     def getOutPortValue(self, nodeNumid, portName):
70       try:
71         return self.p.getOutPortValue(nodeNumid, portName)
72       except:
73         traceback.print_exc()
74         return ""
75
76     def getErrorDetails(self, nodeNumid):
77         return self.p.getNodeErrorDetails(nodeNumid)
78
79     def getErrorReport(self, nodeNumid):
80         return self.p.getNodeErrorReport(nodeNumid)
81
82     def getContainerLog(self, nodeNumid):
83         return self.p.getNodeContainerLog(nodeNumid)
84
85     def shutdownProc(self, level):
86         return self.p.shutdown(level)
87
88     def getExecutorState(self):
89         return self.e.getExecutorState()
90
91     def getIds(self):
92         numids = self.p.getNumIds()
93         ids = self.p.getIds()
94         return (numids,ids)
95
96     def getNumIds(self):
97         return self.p.getNumIds()
98
99     def getNames(self):
100         return self.p.getIds()
101
102     def runProc(self,debug, isPyThread, fromscratch):
103       print("**************************Begin schema execution %s**************************" % self.xmlFile)
104       self.e.RunPy(self.p,debug, isPyThread, fromscratch)
105       print("**************************End schema execution %s****************************" % self.xmlFile)
106
107     def Run(self):
108         if self.run1 is not None:
109           execState = self.e.getExecutorState()
110           if execState >= pilot.FINISHED:
111             self.run1.join()
112             self.run1 = None
113
114         if self.run1 is None:
115             self.run1 = threading.Thread(None, self.runProc, "CORBAExec", (0,True,True))
116             self.run1.start()
117
118     def RunFromState(self, xmlFile):
119         """Start an execution from the state given by the file xmlFile
120            If xmlFile == "", start execution from the current state
121         """
122         if self.run1 is not None:
123           execState = self.e.getExecutorState()
124           if execState >= pilot.FINISHED:
125             self.run1.join()
126             self.run1 = None
127
128         if xmlFile:
129           try:
130             self.p.init()
131             self.p.exUpdateState();
132             sp = loader.stateParser()
133             sl = loader.stateLoader(sp,self.p)
134             sl.parse(xmlFile)
135           except IOError as ex:
136             print("IO Error: ", ex)
137             return
138           except ValueError as ex:
139             print("Caught ValueError Exception:",ex)
140             return
141           except pilot.Exception as ex:
142             print(ex.what())
143             return
144           except:
145             print("Unknown exception!")
146             return
147
148         if self.run1 is None:
149             self.run1 = threading.Thread(None, self.runProc, "CORBAExec", (0,True,False))
150             self.run1.start()
151
152     def RestartFromState(self, xmlFile):
153         """Reset the procedure state to ready state for all nodes in error
154            if xmlFile exists first try to load the state from this file.
155            then start execution
156         """
157         if self.run1 is not None:
158           execState = self.e.getExecutorState()
159           if execState >= pilot.FINISHED:
160             self.run1.join()
161             self.run1 = None
162           else:
163             return
164
165         try:
166           if os.path.exists(xmlFile):
167             self.p.init()
168             sp = loader.stateParser()
169             sl = loader.stateLoader(sp,self.p)
170             sl.parse(xmlFile)
171
172           self.p.resetState(1)
173           self.p.exUpdateState();
174         except:
175             pass
176
177         if self.run1 is None:
178             self.run1 = threading.Thread(None, self.runProc, "CORBAExec", (0,True,False))
179             self.run1.start()
180
181     def addObserver(self, obs, numid, event):
182         disp = SALOMERuntime.SALOMEDispatcher_getSALOMEDispatcher()
183         disp.addObserver(obs, numid, event)
184         pass
185
186     def setExecMode(self, mode):
187         if mode == YACS_ORB.CONTINUE:
188             self.e.setExecMode(0)
189             pass
190         if mode == YACS_ORB.STEPBYSTEP:
191             self.e.setExecMode(1)
192             pass
193         if mode == YACS_ORB.STOPBEFORENODES:
194             self.e.setExecMode(2)
195             pass
196         pass
197
198     def setListOfBreakPoints(self, listOfBreakPoints):
199         self.e.setListOfBreakPoints(listOfBreakPoints)
200         pass
201
202     def getTasksToLoad(self):
203         return self.e.getTasksToLoad()
204
205     def setStepsToExecute(self, listToExecute):
206         return self.e.setStepsToExecute(listToExecute)
207
208     def resumeCurrentBreakPoint(self):
209         return self.e.resumeCurrentBreakPoint()
210
211     def isNotFinished(self):
212         return self.e.isNotFinished()
213
214     def stopExecution(self):
215         self.e.stopExecution()
216         pass
217
218     def saveState(self, xmlFile):
219         return self.e.saveState(xmlFile)
220
221     def setStopOnError(self, dumpRequested, xmlFile):
222         self.e.setStopOnError(dumpRequested, xmlFile)
223         pass
224
225     def unsetStopOnError(self):
226         self.e.unsetStopOnError()
227         pass
228
229     pass
230
231
232 class YACS(YACS_ORB__POA.YACS_Gen,
233               SALOME_ComponentPy.SALOME_ComponentPy_i,
234               SALOME_DriverPy.SALOME_DriverPy_i):
235     """
236     To be a SALOME component, this Python class must have the component name
237     (YACS) and inherit the YACS_Gen class build from idl compilation
238     with omniidl and also the class SALOME_ComponentPy_i which defines general
239     SALOME component behaviour.
240     """
241     def __init__ ( self, orb, poa, contID, containerName, instanceName,
242                    interfaceName ):
243         print("YACS.__init__: ", containerName, ';', instanceName)
244         SALOME_ComponentPy.SALOME_ComponentPy_i.__init__(self, orb, poa, contID,
245                                                          containerName, instanceName,
246                                                          interfaceName, False)
247         SALOME_DriverPy.SALOME_DriverPy_i.__init__(self, interfaceName)
248
249         SALOMERuntime.RuntimeSALOME_setRuntime(1)
250         SALOMERuntime.SALOMEDispatcher_setSALOMEDispatcher()
251         r=pilot.getRuntime()
252
253         try:
254           #try to load SALOME module catalogs
255           modul_catalog = self._naming_service.Resolve("/Kernel/ModulCatalog")
256           ior= orb.object_to_string(modul_catalog)
257           cata=r.loadCatalog("session",ior)
258           r.addCatalog(cata)
259         except :
260           pass
261
262     """
263     Get version information.
264     """
265     def getVersion( self ):
266         try:
267             rt = SALOMERuntime.getSALOMERuntime()
268             version = rt.getVersion()
269         except:
270             version = ""
271             pass
272         return version
273
274     def LoadProc(self,xmlFile):
275         """
276         load an XML graph in a YACS::ENGINE::proc, create a CORBA servant
277         associated to the proc, and return a ref on the servant.
278         """
279         try:
280             procExec_i = proc_i(xmlFile)
281             logger=procExec_i.p.getLogger("parser")
282             if not logger.isEmpty():
283               print("The imported file has errors :")
284               print(logger.getStr())
285               sys.stdout.flush()
286               return None
287         except IOError as ex:
288             print("IO Error: ", ex, file=sys.stderr)
289             return None
290         except ValueError as ex:
291             print("Caught ValueError Exception:",ex, file=sys.stderr)
292             return None
293         except pilot.Exception as ex:
294             print(ex.what(), file=sys.stderr)
295             return None
296         except:
297             traceback.print_exc()
298             return None
299         procExec_o = procExec_i._this()
300         return procExec_o
301         
302     def convertSupervFile(self,xmlFile):
303         """
304         load a SUPERV xml graph, convert it and return the new filename.
305         """
306         try:
307             r = pilot.getRuntime()
308             lo = salomeloader.SalomeLoader()
309             e = pilot.ExecutorSwig()
310             p = lo.load(xmlFile)
311             s = pilot.SchemaSave(p)
312             hnd, convertedFile = tempfile.mkstemp(".xml","yacs_","/tmp")
313             s.save(convertedFile)
314             return convertedFile
315         except (IndexError):
316             return ""
317
318     pass
319