Salome HOME
PAL issue 2757: Traiter de manière masquée lâ\80\99exécution de la commande DEBUT...
[tools/yacsgen.git] / module_generator / aster_tmpl.py
1 # Copyright (C) 2009-2013  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 try:
21  from string import Template
22 except:
23  from compat import Template,set
24
25 asterCompo="""
26 import sys,traceback,os
27 import ${module}_ORB__POA
28 import calcium
29 import dsccalcium
30 import SALOME
31 import linecache
32 import shutil
33
34 sys.path=sys.path+[${python_path}]
35 import aster
36 import Accas
37 import Cata.cata
38 from Execution.E_SUPERV import SUPERV
39
40 aster_dir="${aster_dir}"
41
42 try:
43   import numpy
44 except:
45   numpy=None
46
47 #DEFS
48 ${servicesdef}
49 #ENDDEF
50
51 class ${component}(${module}_ORB__POA.${component},dsccalcium.PyDSCComponent,SUPERV):
52   '''
53      To be identified as a SALOME component this Python class
54      must have the same name as the component, inherit omniorb
55      class ${module}_ORB__POA.${component} and DSC class dsccalcium.PyDSCComponent
56      that implements DSC API.
57   '''
58   def __init__ ( self, orb, poa, contID, containerName, instanceName, interfaceName ):
59     dsccalcium.PyDSCComponent.__init__(self, orb, poa,contID,containerName,instanceName,interfaceName)
60     self.argv=[${argv}]
61     #modif pour aster 9.0
62     if hasattr(self,"init_timer"):
63       self.init_timer()
64     #fin modif pour aster 9.0
65     if os.path.exists(os.path.join(aster_dir,"elements")):
66       shutil.copyfile(os.path.join(aster_dir,"elements"),"elem.1")
67     else:
68       shutil.copyfile(os.path.join(aster_dir,"catobj","elements"),"elem.1")
69
70   def init_service(self,service):
71 ${initservice}
72     return False
73
74 ${servicesimpl}
75 """
76 asterCompo=Template(asterCompo)
77
78 asterCEXECompo="""
79 # Par rapport a la version precedente
80 # Chaque service est complete par l'appel initial a Complement
81 # Cette methode rajoute a l'appel du premier service de l'instance un prefixe au fichier de commande
82 # Ce prefixe est fourni dans le fichier fort.99 via as_run et exeaster
83 # Le fichier est lu a la creation du module
84 # Interet: introduire DEBUT() dans ce prefixe pour ne plus avoir a s'en preoccuper (ex: boucle for each)
85 import sys,traceback,os
86 import string
87 import cPickle
88 import ${module}_ORB__POA
89 import calcium
90 import dsccalcium
91 import SALOME
92 import linecache
93 ${importesuperv}
94
95 try:
96   import numpy
97 except:
98   numpy=None
99
100 #DEFS
101 ${servicesdef}
102 #ENDDEF
103
104 class ExecutionError(Exception):
105   '''General exception during execution'''
106
107 class ${component}(${module}_ORB__POA.${component},dsccalcium.PyDSCComponent,SUPERV):
108   '''
109      To be identified as a SALOME component this Python class
110      must have the same name as the component, inherit omniorb
111      class ${module}_ORB__POA.${component} and DSC class dsccalcium.PyDSCComponent
112      that implements DSC API.
113   '''
114   def __init__ ( self, orb, poa, contID, containerName, instanceName, interfaceName ):
115     self.init=0
116     if os.path.isfile('fort.99'):
117       prefixFile = file("fort.99","r")
118       self.prefixJdc = prefixFile.read()
119       prefixFile.close()
120     else:
121       self.prefixJdc = ""
122     dsccalcium.PyDSCComponent.__init__(self, orb, poa,contID,containerName,instanceName,interfaceName)
123
124   def init_service(self,service):
125 ${initservice}
126     return False
127
128   def insertPrefix(self,jdc):
129     if not self.init:
130       jdc = self.prefixJdc + jdc
131     return jdc
132
133   def insertPrePost(self,jdc,prepost):
134     if prepost <> "":
135       exec(prepost)
136       try:
137         jdc = os.linesep + pre + os.linesep + jdc + os.linesep + post + os.linesep
138       except NameError:
139         pass
140     return jdc
141     
142   def interpstring(self,text,args):
143     try:
144       self.jdc.g_context.update(args)
145       CONTEXT.set_current_step(self.jdc)
146       linecache.cache['<string>']=0,None,string.split(text,'\\n'),'<string>'
147       exec text in self.jdc.const_context,self.jdc.g_context
148       CONTEXT.unset_current_step()
149     except EOFError:
150       CONTEXT.unset_current_step()
151     except:
152       CONTEXT.unset_current_step()
153       raise
154
155 ${servicesimpl}
156 """
157
158 asterEXECompo=asterCEXECompo+"""
159   def destroy(self):
160      self._orb.shutdown(0)
161 """
162
163 asterCEXECompo=Template(asterCEXECompo)
164 asterEXECompo=Template(asterEXECompo)
165
166 asterService="""
167   def ${service}(self,${inparams}):
168     self.beginService("${component}.${service}")
169     self.jdc=Cata.cata.JdC(procedure=jdc,cata=Cata.cata,nom="Salome",context_ini=${dvars})
170     j=self.jdc
171     #modif pour aster 9.0
172     if hasattr(self,"init_timer"):
173       j.timer = self.timer
174     #fin modif pour aster 9.0
175
176     # On compile le texte Python
177     j.compile()
178
179     #modif pour aster 9.0
180     # On initialise les tops de mesure globale de temps d'execution du jdc
181     if hasattr(self,"init_timer"):
182        j.cpu_user=os.times()[0]
183        j.cpu_syst=os.times()[1]
184     #fin modif pour aster 9.0
185
186     if not j.cr.estvide():
187        msg="ERREUR DE COMPILATION DANS ACCAS - INTERRUPTION"
188        self.MESSAGE(msg)
189        print ">> JDC.py : DEBUT RAPPORT"
190        print j.cr
191        print ">> JDC.py : FIN RAPPORT"
192        j.supprime()
193        sys.stdout.flush()
194        raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(j.cr),"${component}.py",0))
195
196     #surcharge des arguments de la ligne de commande (defaut stocke dans le composant) par un eventuel port de nom argv
197     try:
198       self.argv=self.argv+argv.split()
199     except:
200       pass
201
202     #initialisation des arguments de la ligne de commande (remplace la methode initexec de B_JDC.py)
203     aster.argv(self.argv)
204     aster.init(CONTEXT.debug)
205     j.setmode(1)
206     j.ini=1
207
208     try:
209       j.exec_compile()
210     except:
211       sys.stdout.flush()
212       exc_typ,exc_val,exc_fr=sys.exc_info()
213       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
214       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"${component}.py",0))
215
216     ier=0
217     if not j.cr.estvide():
218        msg="ERREUR A L'INTERPRETATION DANS ACCAS - INTERRUPTION"
219        self.MESSAGE(msg)
220        ier=1
221        print ">> JDC.py : DEBUT RAPPORT"
222        print j.cr
223        print ">> JDC.py : FIN RAPPORT"
224        sys.stdout.flush()
225        raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(j.cr), "${component}.py",0))
226
227     if j.par_lot == 'NON':
228        print "FIN EXECUTION"
229        #err=calcium.cp_fin(self.proxy,calcium.CP_ARRET)
230        #retour sans erreur (il faut pousser les variables de sortie)
231        sys.stdout.flush()
232        self.endService("${component}.${service}")
233        return ${rvars}
234
235     # Verification de la validite du jeu de commande
236     cr=j.report()
237     if not cr.estvide():
238        msg="ERREUR A LA VERIFICATION SYNTAXIQUE - INTERRUPTION"
239        self.MESSAGE(msg)
240        print ">> JDC.py : DEBUT RAPPORT"
241        print cr
242        print ">> JDC.py : FIN RAPPORT"
243        sys.stdout.flush()
244        raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(cr),"${component}.py",0))
245
246     j.set_par_lot("NON")
247     try:
248        j.BuildExec()
249        ier=0
250        if not j.cr.estvide():
251           msg="ERREUR A L'EXECUTION - INTERRUPTION"
252           self.MESSAGE(msg)
253           ier=1
254           print ">> JDC.py : DEBUT RAPPORT"
255           print j.cr
256           print ">> JDC.py : FIN RAPPORT"
257           sys.stdout.flush()
258           raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,msg+'\\n'+str(j.cr),"${component}.py",0))
259        else:
260          #retour sans erreur (il faut pousser les variables de sortie)
261          #err=calcium.cp_fin(self.proxy,calcium.CP_ARRET)
262          sys.stdout.flush()
263          self.endService("${component}.${service}")
264          return ${rvars}
265     except :
266       self.MESSAGE("ERREUR INOPINEE - INTERRUPTION")
267       sys.stdout.flush()
268       exc_typ,exc_val,exc_fr=sys.exc_info()
269       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
270       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"${component}.py",0))
271 """
272 asterService=Template(asterService)
273
274 asterCEXEService="""
275   def ${service}(self,${inparams}):
276     self.beginService("${component}.${service}")
277     try:
278       args=${dvars}
279       if not args.has_key("jdc"):
280         fcomm=open("jdc",'r')
281         jdc=fcomm.read()
282         fcomm.close()
283         #args["jdc"]=jdc
284       prepost = '''${body}'''
285       jdc = self.insertPrePost(jdc,prepost)
286       jdc = self.insertPrefix(jdc)
287       if not self.init:
288         self.init=1
289         fcomm=open("fort.1",'w')
290         fcomm.write(jdc)
291         fcomm.close()
292         ier=self.main(args)
293         if ier != 0:
294           raise ExecutionError("Error in initial execution")
295       else:
296         self.interpstring(jdc,args)
297
298       self.endService("${component}.${service}")
299       j=self.jdc
300       return ${rvars}
301     except:
302       exc_typ,exc_val,exc_fr=sys.exc_info()
303       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
304       self.endService("${component}.${service}")
305       sys.stdout.flush()
306       sys.stderr.flush()
307       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"${component}.py",0))
308 """
309 asterCEXEService=Template(asterCEXEService)
310 asterEXEService=asterCEXEService
311
312
313 check_aster="""
314 #
315 # Check availability of Aster binary distribution
316 #
317
318 AC_DEFUN([AC_CHECK_ASTER],[
319
320 AC_CHECKING(for Aster)
321
322 Aster_ok=no
323
324 AC_ARG_WITH(aster,
325       [AC_HELP_STRING([--with-aster=DIR],[root directory path of Aster installation])],
326       [ASTER_DIR="$withval"],[ASTER_DIR=""])
327
328 if test -f ${ASTER_DIR}/asteru ; then
329    Aster_ok=yes
330    AC_MSG_RESULT(Using Aster distribution in ${ASTER_DIR})
331
332    ASTER_INCLUDES=-I$ASTER_DIR/bibc/include
333
334    AC_SUBST(ASTER_DIR)
335    AC_SUBST(ASTER_INCLUDES)
336
337 else
338    AC_MSG_WARN("Cannot find Aster distribution")
339 fi
340
341 AC_MSG_RESULT(for Aster: $Aster_ok)
342
343 ])dnl
344 """
345
346 comm="""
347 DEBUT(PAR_LOT='NON')
348 """
349
350 make_etude="""P actions make_etude
351 P version NEW9
352 P nomjob salome
353 P ncpus 1
354 A memjeveux 4.000000
355 P mem_aster 100
356 A tpmax 60
357 P memjob 32768
358 P mpi_nbcpu 1
359 P mpi_nbnoeud 1
360 P tpsjob 1
361 P mode batch
362 P soumbtc oui
363 P consbtc oui
364 F conf ${config} D 0
365 F comm ${comm} D 1
366 ${extras}
367 """
368 make_etude=Template(make_etude)
369
370 make_etude_exe="""P actions make_etude
371 P version NEW9
372 P nomjob salome
373 P ncpus 1
374 A memjeveux 4.000000
375 P mem_aster 100
376 A tpmax 60
377 P memjob 32768
378 P mpi_nbcpu 1
379 P mpi_nbnoeud 1
380 P tpsjob 1
381 P mode batch
382 P soumbtc oui
383 P consbtc oui
384 F comm ${comm} D 1
385 """
386 make_etude_exe=Template(make_etude_exe)
387
388 cexe="""#!/bin/sh
389
390 export SALOME_CONTAINERNAME=$$1
391
392 ${compoexe}
393 """
394 cexe=Template(cexe)
395
396 exeaster="""#!/bin/sh
397
398 export SALOME_CONTAINER=$$1
399 export SALOME_CONTAINERNAME=$$2
400 export SALOME_INSTANCE=$$3
401
402 ${compoexe}
403 """
404 exeaster=Template(exeaster)
405
406 container="""import sys,os
407 from omniORB import CORBA
408 from SALOME_ContainerPy import SALOME_ContainerPy_i
409
410 if __name__ == '__main__':
411
412   print sys.argv
413   orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
414   poa = orb.resolve_initial_references("RootPOA")
415   print "ORB and POA initialized"
416   containerName=os.getenv("SALOME_CONTAINERNAME")
417   cpy_i = SALOME_ContainerPy_i(orb, poa, containerName)
418   print "SALOME_ContainerPy_i instance created ",cpy_i
419   cpy_o = cpy_i._this()
420   print "SALOME_ContainerPy_i instance activated ",cpy_o
421   sys.stdout.flush()
422   sys.stderr.flush()
423
424   #activate the POA
425   poaManager = poa._get_the_POAManager()
426   poaManager.activate()
427
428   #Block for ever
429   orb.run()
430   print "fin container aster"
431   sys.stdout.flush()
432   sys.stderr.flush()
433 """
434
435 component="""import sys,os
436 from omniORB import CORBA
437 from ${component}_module import ${component}
438
439 if __name__ == '__main__':
440
441   print sys.argv
442   orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
443   poa = orb.resolve_initial_references("RootPOA")
444   print "ORB and POA initialized",orb,poa
445   sys.stdout.flush()
446   sys.stderr.flush()
447
448   container=orb.string_to_object(os.getenv("SALOME_CONTAINER"))
449   containerName=os.getenv("SALOME_CONTAINERNAME")
450   instanceName=os.getenv("SALOME_INSTANCE")
451
452   compo=${component}(orb,poa,container,containerName, instanceName, "${component}")
453   comp_o = compo._this()
454   comp_iors = orb.object_to_string(comp_o)
455   print "ior aster",comp_iors
456
457   sys.stdout.flush()
458   sys.stderr.flush()
459
460   #activate the POA
461   poaManager = poa._get_the_POAManager()
462   poaManager.activate()
463
464   orb.run()
465   print "fin du composant aster standalone"
466
467 """
468 component=Template(component)
469