Salome HOME
d98ae6cfa5c533161b6d00c37fe921489afd4f8f
[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 ActivateProxyMecanismOrNot( sizeInByte ):
171   thres = GetBigObjectOnDiskThreshold()
172   if thres == -1:
173     return False
174   else:
175     return sizeInByte > thres
176
177 def GetBigObjectDirectory():
178   import os
179   if SALOME_FILE_BIG_OBJ_DIR not in os.environ:
180     raise RuntimeError("An object of size higher than limit detected and no directory specified to dump it in file !")
181   return os.path.expanduser( os.path.expandvars( os.environ[SALOME_FILE_BIG_OBJ_DIR] ) )
182
183 def GetBigObjectFileName():
184   """
185   Return a filename in the most secure manner (see tempfile documentation)
186   """
187   import tempfile
188   with tempfile.NamedTemporaryFile(dir=GetBigObjectDirectory(),prefix="mem_",suffix=".pckl") as f:
189     ret = f.name
190   return ret
191
192 class BigObjectOnDiskBase:
193   def __init__(self, fileName, objSerialized):
194     """
195     :param fileName: the file used to dump into.
196     :param objSerialized: the object in pickeled form
197     :type objSerialized: bytes
198     """
199     self._filename = fileName
200     # attribute _destroy is here to tell client side or server side
201     # only client side can be with _destroy set to True. server side due to risk of concurrency
202     # so pickled form of self must be done with this attribute set to False.
203     self._destroy = False
204     self.__dumpIntoFile(objSerialized)
205
206   def getDestroyStatus(self):
207     return self._destroy
208
209   def incrRef(self):
210     if self._destroy:
211       IncrRefInFile( self._filename )
212     else:
213       # should never happen !
214       RuntimeError("Invalid call to incrRef !")
215
216   def decrRef(self):
217     if self._destroy:
218       DecrRefInFile( self._filename )
219     else:
220       # should never happen !
221       RuntimeError("Invalid call to decrRef !")
222
223   def unlinkOnDestructor(self):
224     self._destroy = True
225
226   def doNotTouchFile(self):
227     """
228     Method called slave side. The life cycle management of file is client side not slave side.
229     """
230     self._destroy = False
231
232   def __del__(self):
233     if self._destroy:
234       DecrRefInFile( self._filename )
235
236   def getFileName(self):
237     return self._filename
238   
239   def __dumpIntoFile(self, objSerialized):
240     DumpInFile( objSerialized, self._filename )
241
242   def get(self):
243     obj, _ = GetObjectFromFile( self._filename )
244     return obj
245
246   def __float__(self):
247     return float( self.get() )
248     
249   def __int__(self):
250     return int( self.get() )
251     
252   def __str__(self):
253     obj = self.get()
254     if isinstance(obj,str):
255         return obj
256     else:
257         raise RuntimeError("Not a string")
258       
259 class BigObjectOnDisk(BigObjectOnDiskBase):
260   def __init__(self, fileName, objSerialized):
261     BigObjectOnDiskBase.__init__(self, fileName, objSerialized)
262     
263 class BigObjectOnDiskListElement(BigObjectOnDiskBase):
264   def __init__(self, pos, length, fileName):
265     self._filename = fileName
266     self._destroy = False
267     self._pos = pos
268     self._length = length
269
270   def get(self):
271     fullObj = BigObjectOnDiskBase.get(self)
272     return fullObj[ self._pos ]
273     
274   def __getitem__(self, i):
275     return self.get()[i]
276
277   def __len__(self):
278     return len(self.get())
279     
280 class BigObjectOnDiskSequence(BigObjectOnDiskBase):
281   def __init__(self, length, fileName, objSerialized):
282     BigObjectOnDiskBase.__init__(self, fileName, objSerialized)
283     self._length = length
284
285   def __getitem__(self, i):
286     return BigObjectOnDiskListElement(i, self._length, self.getFileName())
287
288   def __len__(self):
289     return self._length
290
291 class BigObjectOnDiskList(BigObjectOnDiskSequence):
292   def __init__(self, length, fileName, objSerialized):
293     BigObjectOnDiskSequence.__init__(self, length, fileName, objSerialized)
294     
295 class BigObjectOnDiskTuple(BigObjectOnDiskSequence):
296   def __init__(self, length, fileName, objSerialized):
297     BigObjectOnDiskSequence.__init__(self, length, fileName, objSerialized)
298
299 def SpoolPickleObject( obj ):
300   import pickle
301   pickleObjInit = pickle.dumps( obj , pickle.HIGHEST_PROTOCOL )
302   if not ActivateProxyMecanismOrNot( len(pickleObjInit) ):
303     return pickleObjInit
304   else:
305     if isinstance( obj, list):
306       proxyObj = BigObjectOnDiskList( len(obj), GetBigObjectFileName() , pickleObjInit )
307     elif isinstance( obj, tuple):
308       proxyObj = BigObjectOnDiskTuple( len(obj), GetBigObjectFileName() , pickleObjInit )
309     else:
310       proxyObj = BigObjectOnDisk( GetBigObjectFileName() , pickleObjInit )
311     pickleProxy = pickle.dumps( proxyObj , pickle.HIGHEST_PROTOCOL )
312     return pickleProxy
313
314 def UnProxyObjectSimple( obj ):
315   """
316   Method to be called in Remote mode. Alterate the obj _status attribute. 
317   Because the slave process does not participate in the reference counting
318   """
319   if isinstance(obj,BigObjectOnDiskBase):
320     obj.doNotTouchFile()
321     return obj.get()
322   elif isinstance( obj, list):
323     retObj = []
324     for elt in obj:
325       retObj.append( UnProxyObjectSimple(elt) )
326     return retObj
327   else:
328     return obj
329
330 def UnProxyObjectSimpleLocal( obj ):
331   """
332   Method to be called in Local mode. Do not alterate the PyObj counter
333   """
334   if isinstance(obj,BigObjectOnDiskBase):
335     return obj.get()
336   elif isinstance( obj, list):
337     retObj = []
338     for elt in obj:
339       retObj.append( UnProxyObjectSimpleLocal(elt) )
340     return retObj
341   else:
342     return obj
343     
344 class SeqByteReceiver:
345   # 2GB limit to trigger split into chunks
346   CHUNK_SIZE = 2000000000
347   def __init__(self,sender):
348     self._obj = sender
349   def __del__(self):
350     self._obj.UnRegister()
351     pass
352   def data(self):
353     size = self._obj.getSize()
354     if size <= SeqByteReceiver.CHUNK_SIZE:
355       return self.fetchOneShot( size )
356     else:
357       return self.fetchByChunks( size )
358   def fetchOneShot(self,size):
359     return self._obj.sendPart(0,size)
360   def fetchByChunks(self,size):
361       """
362       To avoid memory peak parts over 2GB are sent using EFF_CHUNK_SIZE size.
363       """
364       data_for_split_case = bytes(0)
365       EFF_CHUNK_SIZE = SeqByteReceiver.CHUNK_SIZE // 8
366       iStart = 0 ; iEnd = EFF_CHUNK_SIZE
367       while iStart!=iEnd and iEnd <= size:
368         part = self._obj.sendPart(iStart,iEnd)
369         data_for_split_case = bytes(0).join( [data_for_split_case,part] )
370         iStart = iEnd; iEnd = min(iStart + EFF_CHUNK_SIZE,size)
371       return data_for_split_case
372
373 class PyScriptNode_i (Engines__POA.PyScriptNode,Generic):
374   """The implementation of the PyScriptNode CORBA IDL that executes a script"""
375   def __init__(self, nodeName,code,poa,my_container):
376     """Initialize the node : compilation in the local context"""
377     Generic.__init__(self,poa)
378     self.nodeName=nodeName
379     self.code=code
380     self.my_container=my_container._container
381     linecache.cache[nodeName]=0,None,code.split('\n'),nodeName
382     self.ccode=compile(code,nodeName,'exec')
383     self.context={}
384     self.context[MY_CONTAINER_ENTRY_IN_GLBS] = self.my_container
385     
386   def __del__(self):
387     # force removal of self.context. Don t know why it s not done by default
388     self.removeAllVarsInContext()
389     pass
390
391   def getContainer(self):
392     return self.my_container
393
394   def getCode(self):
395     return self.code
396
397   def getName(self):
398     return self.nodeName
399
400   def defineNewCustomVar(self,varName,valueOfVar):
401     self.context[varName] = pickle.loads(valueOfVar)
402     pass
403
404   def executeAnotherPieceOfCode(self,code):
405     """Called for initialization of container lodging self."""
406     try:
407       ccode=compile(code,self.nodeName,'exec')
408       exec(ccode, self.context)
409     except Exception:
410       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode (%s) : code to be executed \"%s\"" %(self.nodeName,code),0))
411
412   def assignNewCompiledCode(self,codeStr):
413     try:
414       self.code=codeStr
415       self.ccode=compile(codeStr,self.nodeName,'exec')
416     except Exception:
417       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode.assignNewCompiledCode (%s) : code to be executed \"%s\"" %(self.nodeName,codeStr),0))
418
419   def executeSimple(self, key, val):
420     """
421     Same as execute method except that no pickelization mecanism is implied here. No output is expected
422     """
423     try:
424       self.context.update({ "env" : [(k,v) for k,v in zip(key,val)]})
425       exec(self.ccode,self.context)
426     except Exception:
427       exc_typ,exc_val,exc_fr=sys.exc_info()
428       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
429       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" % (self.nodeName),0))
430     
431   def execute(self,outargsname,argsin):
432     """Execute the script stored in attribute ccode with pickled args (argsin)"""
433     try:
434       argsname,kws=pickle.loads(argsin)
435       self.context.update(kws)
436       exec(self.ccode, self.context)
437       argsout=[]
438       for arg in outargsname:
439         if arg not in self.context:
440           raise KeyError("There is no variable %s in context" % arg)
441         argsout.append(self.context[arg])
442       argsout=pickle.dumps(tuple(argsout),-1)
443       return argsout
444     except Exception:
445       exc_typ,exc_val,exc_fr=sys.exc_info()
446       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
447       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s, outargsname: %s" % (self.nodeName,outargsname),0))
448
449   def executeFirst(self,argsin):
450     """ Same than first part of self.execute to reduce memory peak."""
451     import time
452     try:
453       data = None
454       if True: # to force call of SeqByteReceiver's destructor
455         argsInPy = SeqByteReceiver( argsin )
456         data = argsInPy.data()
457       _,kws=pickle.loads(data)
458       for elt in kws:
459         # fetch real data if necessary
460         kws[elt] = UnProxyObjectSimple( kws[elt] )
461       self.context.update(kws)
462     except Exception:
463       exc_typ,exc_val,exc_fr=sys.exc_info()
464       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
465       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode:First %s" % (self.nodeName),0))
466
467   def executeSecond(self,outargsname):
468     """ Same than second part of self.execute to reduce memory peak."""
469     try:
470       exec(self.ccode, self.context)
471       argsout=[]
472       for arg in outargsname:
473         if arg not in self.context:
474           raise KeyError("There is no variable %s in context" % arg)
475         argsout.append(self.context[arg])
476       ret = [ ]
477       for arg in argsout:
478         # the proxy mecanism is catched here
479         argPickle = SpoolPickleObject( arg )
480         retArg = SenderByte_i( self.poa,argPickle )
481         id_o = self.poa.activate_object(retArg)
482         retObj = self.poa.id_to_reference(id_o)
483         ret.append( retObj._narrow( SALOME.SenderByte ) )
484       return ret
485     except Exception:
486       exc_typ,exc_val,exc_fr=sys.exc_info()
487       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
488       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode:Second %s, outargsname: %s" % (self.nodeName,outargsname),0))
489
490   def listAllVarsInContext(self):
491       import re
492       pat = re.compile("^__([a-z]+)__$")
493       return [elt for elt in self.context if not pat.match(elt) and elt != MY_CONTAINER_ENTRY_IN_GLBS]
494       
495   def removeAllVarsInContext(self):
496       for elt in self.listAllVarsInContext():
497         del self.context[elt]
498
499   def getValueOfVarInContext(self,varName):
500     try:
501       return pickle.dumps(self.context[varName],-1)
502     except Exception:
503       exc_typ,exc_val,exc_fr=sys.exc_info()
504       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
505       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0))
506     pass
507   
508   def assignVarInContext(self, varName, value):
509     try:
510       self.context[varName][0] = pickle.loads(value)
511     except Exception:
512       exc_typ,exc_val,exc_fr=sys.exc_info()
513       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
514       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0))
515     pass
516
517   def callMethodOnVarInContext(self, varName, methodName, args):
518     try:
519       return pickle.dumps( getattr(self.context[varName][0],methodName)(*pickle.loads(args)),-1 )
520     except Exception:
521       exc_typ,exc_val,exc_fr=sys.exc_info()
522       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
523       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0))
524     pass