Salome HOME
36ca3a2900a2d43e8cf03a8f8a9a0cb05be3eee4
[modules/yacs.git] / src / yacsorb / YACS.py
1 # Copyright (C) 2006-2012  CEA/DEN, EDF R&D
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.
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 getXMLState(self, numid):
50         return self.p.getXMLState(numid)
51
52     def getInPortValue(self, nodeNumid, portName):
53       try:
54         return self.p.getInPortValue(nodeNumid, portName)
55       except:
56         traceback.print_exc()
57         return ""
58
59     def setInPortValue(self, nodeName, portName, value):
60       try:
61         return self.p.setInPortValue(nodeName, portName, value)
62       except:
63         traceback.print_exc()
64         return ""
65
66     def getOutPortValue(self, nodeNumid, portName):
67       try:
68         return self.p.getOutPortValue(nodeNumid, portName)
69       except:
70         traceback.print_exc()
71         return ""
72
73     def getErrorDetails(self, nodeNumid):
74         return self.p.getNodeErrorDetails(nodeNumid)
75
76     def getErrorReport(self, nodeNumid):
77         return self.p.getNodeErrorReport(nodeNumid)
78
79     def getContainerLog(self, nodeNumid):
80         return self.p.getNodeContainerLog(nodeNumid)
81
82     def shutdownProc(self, level):
83         return self.p.shutdown(level)
84
85     def getExecutorState(self):
86         return self.e.getExecutorState()
87
88     def getIds(self):
89         numids = self.p.getNumIds()
90         ids = self.p.getIds()
91         return (numids,ids)
92
93     def getNumIds(self):
94         return self.p.getNumIds()
95
96     def getNames(self):
97         return self.p.getIds()
98
99     def runProc(self,debug, isPyThread, fromscratch):
100       print "**************************Begin schema execution %s**************************" % self.xmlFile
101       self.e.RunPy(self.p,debug, isPyThread, fromscratch)
102       print "**************************End schema execution %s****************************" % self.xmlFile
103
104     def Run(self):
105         if self.run1 is not None:
106           execState = self.e.getExecutorState()
107           if execState >= pilot.FINISHED:
108             self.run1.join()
109             self.run1 = None
110
111         if self.run1 is None:
112             self.run1 = threading.Thread(None, self.runProc, "CORBAExec", (0,1,1))
113             self.run1.start()
114
115     def RunFromState(self, xmlFile):
116         """Start an execution from the state given by the file xmlFile
117            If xmlFile == "", start execution from the current state
118         """
119         if self.run1 is not None:
120           execState = self.e.getExecutorState()
121           if execState >= pilot.FINISHED:
122             self.run1.join()
123             self.run1 = None
124
125         if xmlFile:
126           try:
127             self.p.init()
128             self.p.exUpdateState();
129             sp = loader.stateParser()
130             sl = loader.stateLoader(sp,self.p)
131             sl.parse(xmlFile)
132           except IOError, ex:
133             print "IO Error: ", ex
134             return
135           except ValueError,ex:
136             print "Caught ValueError Exception:",ex
137             return
138           except pilot.Exception,ex:
139             print ex.what()
140             return
141           except:
142             print "Unknown exception!"
143             return
144
145         if self.run1 is None:
146             self.run1 = threading.Thread(None, self.runProc, "CORBAExec", (0,1,0))
147             self.run1.start()
148
149     def RestartFromState(self, xmlFile):
150         """Reset the procedure state to ready state for all nodes in error
151            if xmlFile exists first try to load the state from this file.
152            then start execution
153         """
154         if self.run1 is not None:
155           execState = self.e.getExecutorState()
156           if execState >= pilot.FINISHED:
157             self.run1.join()
158             self.run1 = None
159           else:
160             return
161
162         try:
163           if os.path.exists(xmlFile):
164             self.p.init()
165             sp = loader.stateParser()
166             sl = loader.stateLoader(sp,self.p)
167             sl.parse(xmlFile)
168
169           self.p.resetState(1)
170           self.p.exUpdateState();
171         except:
172             pass
173
174         if self.run1 is None:
175             self.run1 = threading.Thread(None, self.runProc, "CORBAExec", (0,1,0))
176             self.run1.start()
177
178     def addObserver(self, obs, numid, event):
179         disp = SALOMERuntime.SALOMEDispatcher_getSALOMEDispatcher()
180         disp.addObserver(obs, numid, event)
181         pass
182
183     def setExecMode(self, mode):
184         if mode == YACS_ORB.CONTINUE:
185             self.e.setExecMode(0)
186             pass
187         if mode == YACS_ORB.STEPBYSTEP:
188             self.e.setExecMode(1)
189             pass
190         if mode == YACS_ORB.STOPBEFORENODES:
191             self.e.setExecMode(2)
192             pass
193         pass
194
195     def setListOfBreakPoints(self, listOfBreakPoints):
196         self.e.setListOfBreakPoints(listOfBreakPoints)
197         pass
198
199     def getTasksToLoad(self):
200         return self.e.getTasksToLoad()
201
202     def setStepsToExecute(self, listToExecute):
203         return self.e.setStepsToExecute(listToExecute)
204
205     def resumeCurrentBreakPoint(self):
206         return self.e.resumeCurrentBreakPoint()
207
208     def isNotFinished(self):
209         return self.e.isNotFinished()
210
211     def stopExecution(self):
212         self.e.stopExecution()
213         pass
214
215     def saveState(self, xmlFile):
216         return self.e.saveState(xmlFile)
217
218     def setStopOnError(self, dumpRequested, xmlFile):
219         self.e.setStopOnError(dumpRequested, xmlFile)
220         pass
221
222     def unsetStopOnError(self):
223         self.e.unsetStopOnError()
224         pass
225
226     pass
227
228
229 class YACS(YACS_ORB__POA.YACS_Gen,
230               SALOME_ComponentPy.SALOME_ComponentPy_i,
231               SALOME_DriverPy.SALOME_DriverPy_i):
232     """
233     To be a SALOME component, this Python class must have the component name
234     (YACS) and inherit the YACS_Gen class build from idl compilation
235     with omniidl and also the class SALOME_ComponentPy_i which defines general
236     SALOME component behaviour.
237     """
238     def __init__ ( self, orb, poa, contID, containerName, instanceName,
239                    interfaceName ):
240         print "YACS.__init__: ", containerName, ';', instanceName
241         SALOME_ComponentPy.SALOME_ComponentPy_i.__init__(self, orb, poa, contID,
242                                                          containerName, instanceName,
243                                                          interfaceName, 0)
244         SALOME_DriverPy.SALOME_DriverPy_i.__init__(self, interfaceName)
245
246         # --- store a naming service interface instance in _naming_service atribute
247         self._naming_service = SALOME_ComponentPy.SALOME_NamingServicePy_i( self._orb )
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     def LoadProc(self,xmlFile):
263         """
264         load an XML graph in a YACS::ENGINE::proc, create a CORBA servant
265         associated to the proc, and return a ref on the servant.
266         """
267         try:
268             procExec_i = proc_i(xmlFile)
269             logger=procExec_i.p.getLogger("parser")
270             if not logger.isEmpty():
271               print "The imported file has errors :"
272               print logger.getStr()
273               sys.stdout.flush()
274               return None
275         except IOError, ex:
276             print >> sys.stderr ,"IO Error: ", ex
277             return None
278         except ValueError,ex:
279             print >> sys.stderr ,"Caught ValueError Exception:",ex
280             return None
281         except pilot.Exception,ex:
282             print >> sys.stderr ,ex.what()
283             return None
284         except:
285             traceback.print_exc()
286             return None
287         procExec_o = procExec_i._this()
288         return procExec_o
289         
290     def convertSupervFile(self,xmlFile):
291         """
292         load a SUPERV xml graph, convert it and return the new filename.
293         """
294         try:
295             r = pilot.getRuntime()
296             lo = salomeloader.SalomeLoader()
297             e = pilot.ExecutorSwig()
298             p = lo.load(xmlFile)
299             s = pilot.SchemaSave(p)
300             hnd, convertedFile = tempfile.mkstemp(".xml","yacs_","/tmp")
301             s.save(convertedFile)
302             return convertedFile
303         except (IndexError):
304             return ""
305
306     pass
307