Salome HOME
Avoid additionnal CORBA invocation to clear context
[modules/kernel.git] / src / Container / SALOME_PyNode.py
1 #  -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2023  CEA, EDF, OPEN CASCADE
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License, or (at your option) any later version.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20
21 #  File   : SALOME_PyNode.py
22 #  Author : Christian CAREMOLI, EDF
23 #  Module : SALOME
24 #  $Header$
25 #
26 import sys,traceback
27 import linecache
28 import pickle
29 import Engines__POA
30 import SALOME__POA
31 import SALOME
32
33 MY_CONTAINER_ENTRY_IN_GLBS = "my_container"
34
35 class Generic(SALOME__POA.GenericObj):
36   """A Python implementation of the GenericObj CORBA IDL"""
37   def __init__(self,poa):
38     self.poa=poa
39     self.cnt=1
40
41   def Register(self):
42     #print("Register called : %d"%self.cnt)
43     self.cnt+=1
44
45   def UnRegister(self):
46     #print("UnRegister called : %d"%self.cnt)
47     self.cnt-=1
48     if self.cnt <= 0:
49       oid=self.poa.servant_to_id(self)
50       self.poa.deactivate_object(oid)
51
52   def Destroy(self):
53     print("WARNING SALOME::GenericObj::Destroy() function is obsolete! Use UnRegister() instead.")
54     self.UnRegister()
55
56   def __del__(self):
57     #print("Destuctor called")
58     pass
59
60 class PyNode_i (Engines__POA.PyNode,Generic):
61   """The implementation of the PyNode CORBA IDL"""
62   def __init__(self, nodeName,code,poa,my_container):
63     """Initialize the node : compilation in the local context"""
64     Generic.__init__(self,poa)
65     self.nodeName=nodeName
66     self.code=code
67     self.my_container=my_container._container
68     linecache.cache[nodeName]=0,None,code.split('\n'),nodeName
69     ccode=compile(code,nodeName,'exec')
70     self.context={}
71     self.context[MY_CONTAINER_ENTRY_IN_GLBS] = self.my_container
72     exec(ccode, self.context)
73
74   def getContainer(self):
75     return self.my_container
76
77   def getCode(self):
78     return self.code
79
80   def getName(self):
81     return self.nodeName
82
83   def defineNewCustomVar(self,varName,valueOfVar):
84     self.context[varName] = pickle.loads(valueOfVar)
85     pass
86
87   def executeAnotherPieceOfCode(self,code):
88     """Called for initialization of container lodging self."""
89     try:
90       ccode=compile(code,self.nodeName,'exec')
91       exec(ccode, self.context)
92     except Exception:
93       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode (%s) : code to be executed \"%s\"" %(self.nodeName,code),0))
94
95   def execute(self,funcName,argsin):
96     """Execute the function funcName found in local context with pickled args (argsin)"""
97     try:
98       argsin,kws=pickle.loads(argsin)
99       func=self.context[funcName]
100       argsout=func(*argsin,**kws)
101       argsout=pickle.dumps(argsout,-1)
102       return argsout
103     except Exception:
104       exc_typ,exc_val,exc_fr=sys.exc_info()
105       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
106       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyNode: %s, function: %s" % (self.nodeName,funcName),0))
107
108 class SenderByte_i(SALOME__POA.SenderByte,Generic):
109   def __init__(self,poa,bytesToSend):
110     Generic.__init__(self,poa)
111     self.bytesToSend = bytesToSend
112
113   def getSize(self):
114     return len(self.bytesToSend)
115
116   def sendPart(self,n1,n2):
117     return self.bytesToSend[n1:n2]
118
119 SALOME_FILE_BIG_OBJ_DIR = "SALOME_FILE_BIG_OBJ_DIR"
120     
121 SALOME_BIG_OBJ_ON_DISK_THRES_VAR = "SALOME_BIG_OBJ_ON_DISK_THRES"
122
123 # default is 50 MB
124 SALOME_BIG_OBJ_ON_DISK_THRES_DFT = 50000000
125
126 from ctypes import c_int
127 TypeCounter = c_int
128
129 def GetSizeOfTCnt():
130   return len( bytes(TypeCounter(0) ) )
131
132 def GetObjectFromFile(fname):
133   with open(fname,"rb") as f:
134     cntb = f.read( GetSizeOfTCnt() )
135     cnt = TypeCounter.from_buffer_copy( cntb ).value
136     obj = pickle.load(f)
137   return obj,cnt
138
139 def DumpInFile(obj,fname):
140   with open(fname,"wb") as f:
141     f.write( bytes( TypeCounter(1) ) )
142     f.write( obj )
143
144 def IncrRefInFile(fname):
145   with open(fname,"rb") as f:
146     cntb = f.read( GetSizeOfTCnt() )
147   cnt = TypeCounter.from_buffer_copy( cntb ).value
148   with open(fname,"rb+") as f:
149     f.write( bytes( TypeCounter(cnt+1) ) )
150
151 def DecrRefInFile(fname):
152   import os
153   with open(fname,"rb") as f:
154     cntb = f.read( GetSizeOfTCnt() )
155   cnt = TypeCounter.from_buffer_copy( cntb ).value
156   #
157   if cnt == 1:
158     os.unlink( fname )
159   else:
160     with open(fname,"rb+") as f:
161         f.write( bytes( TypeCounter(cnt-1) ) )
162
163 def GetBigObjectOnDiskThreshold():
164   import os
165   if SALOME_BIG_OBJ_ON_DISK_THRES_VAR in os.environ:
166     return int( os.environ[SALOME_BIG_OBJ_ON_DISK_THRES_VAR] )
167   else:
168     return SALOME_BIG_OBJ_ON_DISK_THRES_DFT
169
170 def GetBigObjectDirectory():
171   import os
172   if SALOME_FILE_BIG_OBJ_DIR not in os.environ:
173     raise RuntimeError("An object of size higher than limit detected and no directory specified to dump it in file !")
174   return os.path.expanduser( os.path.expandvars( os.environ[SALOME_FILE_BIG_OBJ_DIR] ) )
175
176 def GetBigObjectFileName():
177   """
178   Return a filename in the most secure manner (see tempfile documentation)
179   """
180   import tempfile
181   with tempfile.NamedTemporaryFile(dir=GetBigObjectDirectory(),prefix="mem_",suffix=".pckl") as f:
182     ret = f.name
183   return ret
184
185 class BigObjectOnDiskBase:
186   def __init__(self, fileName, objSerialized):
187     """
188     :param fileName: the file used to dump into.
189     :param objSerialized: the object in pickeled form
190     :type objSerialized: bytes
191     """
192     self._filename = fileName
193     # attribute _destroy is here to tell client side or server side
194     # only client side can be with _destroy set to True. server side due to risk of concurrency
195     # so pickled form of self must be done with this attribute set to False.
196     self._destroy = False
197     self.__dumpIntoFile(objSerialized)
198
199   def getDestroyStatus(self):
200     return self._destroy
201
202   def incrRef(self):
203     if self._destroy:
204       IncrRefInFile( self._filename )
205     else:
206       # should never happen !
207       RuntimeError("Invalid call to incrRef !")
208
209   def decrRef(self):
210     if self._destroy:
211       DecrRefInFile( self._filename )
212     else:
213       # should never happen !
214       RuntimeError("Invalid call to decrRef !")
215
216   def unlinkOnDestructor(self):
217     self._destroy = True
218
219   def doNotTouchFile(self):
220     """
221     Method called slave side. The life cycle management of file is client side not slave side.
222     """
223     self._destroy = False
224
225   def __del__(self):
226     if self._destroy:
227       DecrRefInFile( self._filename )
228
229   def getFileName(self):
230     return self._filename
231   
232   def __dumpIntoFile(self, objSerialized):
233     DumpInFile( objSerialized, self._filename )
234
235   def get(self):
236     obj, _ = GetObjectFromFile( self._filename )
237     return obj
238
239   def __float__(self):
240     return float( self.get() )
241     
242   def __int__(self):
243     return int( self.get() )
244     
245   def __str__(self):
246     obj = self.get()
247     if isinstance(obj,str):
248         return obj
249     else:
250         raise RuntimeError("Not a string")
251       
252 class BigObjectOnDisk(BigObjectOnDiskBase):
253   def __init__(self, fileName, objSerialized):
254     BigObjectOnDiskBase.__init__(self, fileName, objSerialized)
255     
256 class BigObjectOnDiskListElement(BigObjectOnDiskBase):
257   def __init__(self, pos, length, fileName):
258     self._filename = fileName
259     self._destroy = False
260     self._pos = pos
261     self._length = length
262
263   def get(self):
264     fullObj = BigObjectOnDiskBase.get(self)
265     return fullObj[ self._pos ]
266     
267   def __getitem__(self, i):
268     return self.get()[i]
269
270   def __len__(self):
271     return len(self.get())
272     
273 class BigObjectOnDiskSequence(BigObjectOnDiskBase):
274   def __init__(self, length, fileName, objSerialized):
275     BigObjectOnDiskBase.__init__(self, fileName, objSerialized)
276     self._length = length
277
278   def __getitem__(self, i):
279     return BigObjectOnDiskListElement(i, self._length, self.getFileName())
280
281   def __len__(self):
282     return self._length
283
284 class BigObjectOnDiskList(BigObjectOnDiskSequence):
285   def __init__(self, length, fileName, objSerialized):
286     BigObjectOnDiskSequence.__init__(self, length, fileName, objSerialized)
287     
288 class BigObjectOnDiskTuple(BigObjectOnDiskSequence):
289   def __init__(self, length, fileName, objSerialized):
290     BigObjectOnDiskSequence.__init__(self, length, fileName, objSerialized)
291
292 def SpoolPickleObject( obj ):
293   import pickle
294   pickleObjInit = pickle.dumps( obj , pickle.HIGHEST_PROTOCOL )
295   if len(pickleObjInit) < GetBigObjectOnDiskThreshold():
296     return pickleObjInit
297   else:
298     if isinstance( obj, list):
299       proxyObj = BigObjectOnDiskList( len(obj), GetBigObjectFileName() , pickleObjInit )
300     elif isinstance( obj, tuple):
301       proxyObj = BigObjectOnDiskTuple( len(obj), GetBigObjectFileName() , pickleObjInit )
302     else:
303       proxyObj = BigObjectOnDisk( GetBigObjectFileName() , pickleObjInit )
304     pickleProxy = pickle.dumps( proxyObj , pickle.HIGHEST_PROTOCOL )
305     return pickleProxy
306
307 def UnProxyObjectSimple( obj ):
308   """
309   Method to be called in Remote mode. Alterate the obj _status attribute. 
310   Because the slave process does not participate in the reference counting
311   """
312   if isinstance(obj,BigObjectOnDiskBase):
313     obj.doNotTouchFile()
314     return obj.get()
315   elif isinstance( obj, list):
316     retObj = []
317     for elt in obj:
318       retObj.append( UnProxyObjectSimple(elt) )
319     return retObj
320   else:
321     return obj
322
323 def UnProxyObjectSimpleLocal( obj ):
324   """
325   Method to be called in Local mode. Do not alterate the PyObj counter
326   """
327   if isinstance(obj,BigObjectOnDiskBase):
328     return obj.get()
329   elif isinstance( obj, list):
330     retObj = []
331     for elt in obj:
332       retObj.append( UnProxyObjectSimpleLocal(elt) )
333     return retObj
334   else:
335     return obj
336     
337 class SeqByteReceiver:
338   # 2GB limit to trigger split into chunks
339   CHUNK_SIZE = 2000000000
340   def __init__(self,sender):
341     self._obj = sender
342   def __del__(self):
343     self._obj.UnRegister()
344     pass
345   def data(self):
346     size = self._obj.getSize()
347     if size <= SeqByteReceiver.CHUNK_SIZE:
348       return self.fetchOneShot( size )
349     else:
350       return self.fetchByChunks( size )
351   def fetchOneShot(self,size):
352     return self._obj.sendPart(0,size)
353   def fetchByChunks(self,size):
354       """
355       To avoid memory peak parts over 2GB are sent using EFF_CHUNK_SIZE size.
356       """
357       data_for_split_case = bytes(0)
358       EFF_CHUNK_SIZE = SeqByteReceiver.CHUNK_SIZE // 8
359       iStart = 0 ; iEnd = EFF_CHUNK_SIZE
360       while iStart!=iEnd and iEnd <= size:
361         part = self._obj.sendPart(iStart,iEnd)
362         data_for_split_case = bytes(0).join( [data_for_split_case,part] )
363         iStart = iEnd; iEnd = min(iStart + EFF_CHUNK_SIZE,size)
364       return data_for_split_case
365
366 class PyScriptNode_i (Engines__POA.PyScriptNode,Generic):
367   """The implementation of the PyScriptNode CORBA IDL that executes a script"""
368   def __init__(self, nodeName,code,poa,my_container):
369     """Initialize the node : compilation in the local context"""
370     Generic.__init__(self,poa)
371     self.nodeName=nodeName
372     self.code=code
373     self.my_container=my_container._container
374     linecache.cache[nodeName]=0,None,code.split('\n'),nodeName
375     self.ccode=compile(code,nodeName,'exec')
376     self.context={}
377     self.context[MY_CONTAINER_ENTRY_IN_GLBS] = self.my_container
378     
379   def __del__(self):
380     # force removal of self.context. Don t know why it s not done by default
381     self.removeAllVarsInContext()
382     pass
383
384   def getContainer(self):
385     return self.my_container
386
387   def getCode(self):
388     return self.code
389
390   def getName(self):
391     return self.nodeName
392
393   def defineNewCustomVar(self,varName,valueOfVar):
394     self.context[varName] = pickle.loads(valueOfVar)
395     pass
396
397   def executeAnotherPieceOfCode(self,code):
398     """Called for initialization of container lodging self."""
399     try:
400       ccode=compile(code,self.nodeName,'exec')
401       exec(ccode, self.context)
402     except Exception:
403       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode (%s) : code to be executed \"%s\"" %(self.nodeName,code),0))
404
405   def assignNewCompiledCode(self,codeStr):
406     try:
407       self.code=codeStr
408       self.ccode=compile(codeStr,self.nodeName,'exec')
409     except Exception:
410       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode.assignNewCompiledCode (%s) : code to be executed \"%s\"" %(self.nodeName,codeStr),0))
411
412   def execute(self,outargsname,argsin):
413     """Execute the script stored in attribute ccode with pickled args (argsin)"""
414     try:
415       argsname,kws=pickle.loads(argsin)
416       self.context.update(kws)
417       exec(self.ccode, self.context)
418       argsout=[]
419       for arg in outargsname:
420         if arg not in self.context:
421           raise KeyError("There is no variable %s in context" % arg)
422         argsout.append(self.context[arg])
423       argsout=pickle.dumps(tuple(argsout),-1)
424       return argsout
425     except Exception:
426       exc_typ,exc_val,exc_fr=sys.exc_info()
427       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
428       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s, outargsname: %s" % (self.nodeName,outargsname),0))
429
430   def executeFirst(self,argsin):
431     """ Same than first part of self.execute to reduce memory peak."""
432     import time
433     try:
434       data = None
435       if True: # to force call of SeqByteReceiver's destructor
436         argsInPy = SeqByteReceiver( argsin )
437         data = argsInPy.data()
438       _,kws=pickle.loads(data)
439       for elt in kws:
440         # fetch real data if necessary
441         kws[elt] = UnProxyObjectSimple( kws[elt] )
442       self.context.update(kws)
443     except Exception:
444       exc_typ,exc_val,exc_fr=sys.exc_info()
445       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
446       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode:First %s" % (self.nodeName),0))
447
448   def executeSecond(self,outargsname):
449     """ Same than second part of self.execute to reduce memory peak."""
450     try:
451       exec(self.ccode, self.context)
452       argsout=[]
453       for arg in outargsname:
454         if arg not in self.context:
455           raise KeyError("There is no variable %s in context" % arg)
456         argsout.append(self.context[arg])
457       ret = [ ]
458       for arg in argsout:
459         # the proxy mecanism is catched here
460         argPickle = SpoolPickleObject( arg )
461         retArg = SenderByte_i( self.poa,argPickle )
462         id_o = self.poa.activate_object(retArg)
463         retObj = self.poa.id_to_reference(id_o)
464         ret.append( retObj._narrow( SALOME.SenderByte ) )
465       return ret
466     except Exception:
467       exc_typ,exc_val,exc_fr=sys.exc_info()
468       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
469       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode:Second %s, outargsname: %s" % (self.nodeName,outargsname),0))
470
471   def listAllVarsInContext(self):
472       import re
473       pat = re.compile("^__([a-z]+)__$")
474       return [elt for elt in self.context if not pat.match(elt) and elt != MY_CONTAINER_ENTRY_IN_GLBS]
475       
476   def removeAllVarsInContext(self):
477       for elt in self.listAllVarsInContext():
478         del self.context[elt]
479
480   def getValueOfVarInContext(self,varName):
481     try:
482       return pickle.dumps(self.context[varName],-1)
483     except Exception:
484       exc_typ,exc_val,exc_fr=sys.exc_info()
485       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
486       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0))
487     pass
488   
489   def assignVarInContext(self, varName, value):
490     try:
491       self.context[varName][0] = pickle.loads(value)
492     except Exception:
493       exc_typ,exc_val,exc_fr=sys.exc_info()
494       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
495       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0))
496     pass
497
498   def callMethodOnVarInContext(self, varName, methodName, args):
499     try:
500       return pickle.dumps( getattr(self.context[varName][0],methodName)(*pickle.loads(args)),-1 )
501     except Exception:
502       exc_typ,exc_val,exc_fr=sys.exc_info()
503       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
504       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0))
505     pass