Salome HOME
If THERE IS an error when executing script, we should explicitly exit :)
[modules/kernel.git] / bin / runSalome.py
1 #!/usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
4 #
5 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
7 #
8 # This library is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License.
12 #
13 # This library is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 # Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with this library; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
21 #
22 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 #
24
25 ## @package runSalome
26 # \brief Module that provides services to launch SALOME
27 #
28
29 import sys, os, string, glob, time, pickle, re
30 import orbmodule
31 import setenv
32 from launchConfigureParser import verbose
33 from server import process_id, Server
34 import json
35 import subprocess
36
37 # -----------------------------------------------------------------------------
38
39 from killSalome import killAllPorts
40
41 def killLocalPort():
42     """
43     kill servers from a previous SALOME exection, if needed,
44     on the CORBA port given in args of runSalome
45     """
46
47     from killSalomeWithPort import killMyPort
48     my_port=str(args['port'])
49     try:
50         killMyPort(my_port)
51     except:
52         print "problem in killLocalPort()"
53         pass
54     pass
55
56 def givenPortKill(port):
57     """
58     kill servers from a previous SALOME exection, if needed,
59     on the same CORBA port
60     """
61
62     from killSalomeWithPort import killMyPort
63     my_port=port
64     try:
65         killMyPort(my_port)
66     except:
67         print "problem in LocalPortKill(), killMyPort(%s)"%port
68         pass
69     pass
70
71 def kill_salome(args):
72     """
73     Kill servers from previous SALOME executions, if needed;
74     depending on args 'killall' or 'portkill', kill all executions,
75     or only execution on the same CORBA port
76     """
77
78     if args['killall']:
79         killAllPorts()
80     elif args['portkill']:
81         givenPortKill(str(args['port']))
82
83 # -----------------------------------------------------------------------------
84 #
85 # Class definitions to launch CORBA Servers
86 #
87
88 class InterpServer(Server):
89     def __init__(self,args):
90         self.args=args
91         if sys.platform != "win32":
92           env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
93           self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
94         else:
95           self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
96
97     def run(self):
98         global process_id
99         command = self.CMD
100         print "INTERPSERVER::command = ", command
101         if sys.platform == "win32":
102           import win32pm
103           pid = win32pm.spawnpid( string.join(command, " "),'-nc' )
104         else:
105           pid = os.spawnvp(os.P_NOWAIT, command[0], command)
106         process_id[pid]=self.CMD
107         self.PID = pid
108
109 # ---
110
111 def get_cata_path(list_modules,modules_root_dir):
112     """Build a list of catalog paths (cata_path) to initialize the ModuleCatalog server
113     """
114     modules_cata={}
115     cata_path=[]
116
117     for module in list_modules:
118         if modules_root_dir.has_key(module):
119             module_root_dir=modules_root_dir[module]
120             module_cata=module+"Catalog.xml"
121             cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
122
123             if os.path.exists(cata_file):
124                 cata_path.append(cata_file)
125                 modules_cata[module]=cata_file
126             else:
127                 cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources", module_cata)
128                 if os.path.exists(cata_file):
129                     cata_path.append(cata_file)
130                     modules_cata[module]=cata_file
131
132     for path in os.getenv("SALOME_CATALOGS_PATH","").split(os.pathsep):
133         if os.path.exists(path):
134             for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
135                 module_name= os.path.basename(cata_file)[:-11]
136                 if not modules_cata.has_key(module_name):
137                     cata_path.append(cata_file)
138                     modules_cata[module_name]=cata_file
139
140     return cata_path
141
142 _siman_name = None
143 def simanStudyName(args):
144     global _siman_name
145     if _siman_name is None:
146         # siman session paramenters and checkout processing
147         _siman_name = ""
148         if 'siman' in args:
149             siman_data = []
150             for param in [ 'study', 'scenario', 'user']:
151                 siman_param = "siman_%s"%param
152                 if siman_param in args:
153                     siman_data.append(args[siman_param])
154                 else:
155                     print "SIMAN %s must be defined using parameter --siman-%s=XXX" % (siman_param, siman_param)
156                     pass
157                 pass
158             if len(siman_data) == 3:
159                 _siman_name = "_".join(siman_data)
160                 pass
161             pass
162         pass
163     return _siman_name
164
165 class CatalogServer(Server):
166     def __init__(self,args):
167         self.args=args
168         self.initArgs()
169         self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
170         self.SCMD2=[]
171         home_dir=os.getenv('HOME')
172         if home_dir is not None:
173             self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
174
175     def setpath(self,modules_list,modules_root_dir):
176         list_modules = modules_list[:]
177         list_modules.reverse()
178         if self.args["gui"] :
179             list_modules = ["KERNEL", "GUI"] + list_modules
180         else :
181             list_modules = ["KERNEL"] + list_modules
182
183         cata_path=get_cata_path(list_modules,modules_root_dir)
184
185         self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
186
187 # ---
188
189 class SalomeDSServer(Server):
190     def __init__(self,args):
191         self.args=args
192         self.initArgs()
193         self.CMD=['SALOMEDS_Server']
194
195 # ---
196
197 class ConnectionManagerServer(Server):
198     def __init__(self,args):
199         self.args=args
200         self.initArgs()
201         self.CMD=['SALOME_ConnectionManagerServer']
202
203 # ---
204
205 class RegistryServer(Server):
206     def __init__(self,args):
207         self.args=args
208         self.initArgs()
209         self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
210
211 # ---
212
213 class ContainerCPPServer(Server):
214     def __init__(self,args):
215         self.args=args
216         self.initArgs()
217         self.CMD=['SALOME_Container','FactoryServer']
218
219 # ---
220
221 class LoggerServer(Server):
222     def __init__(self,args):
223         self.args=args
224         self.initArgs()
225         from salome_utils import generateFileName
226         if sys.platform == "win32": dirpath = os.environ["HOME"]
227         else:                       dirpath = "/tmp"
228         logfile = generateFileName( dirpath,
229                                     prefix="logger",
230                                     extension="log",
231                                     with_username=True,
232                                     with_hostname=True,
233                                     with_port=True)
234         print "==========================================================="
235         print "Logger server: put log to the file:"
236         print logfile
237         print "==========================================================="
238         self.CMD=['SALOME_Logger_Server', logfile]
239         pass
240     pass # end of LoggerServer class
241
242 # ---
243
244 class SessionServer(Server):
245     def __init__(self,args,modules_list,modules_root_dir):
246         self.args = args.copy()
247         # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
248         #self.args['xterm']=0
249         #
250         self.initArgs()
251         self.SCMD1=['SALOME_Session_Server']
252         self.SCMD2=[]
253         if 'registry' in self.args['embedded']:
254             self.SCMD1+=['--with','Registry',
255                          '(','--salome_session','theSession',')']
256         if 'moduleCatalog' in self.args['embedded']:
257             self.SCMD1+=['--with','ModuleCatalog','(','-common']
258             home_dir=os.getenv('HOME')
259             if home_dir is not None:
260                 self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
261             self.SCMD2+=[')']
262         if 'study' in self.args['embedded']:
263             self.SCMD2+=['--with','SALOMEDS','(',')']
264         if 'cppContainer' in self.args['embedded']:
265             self.SCMD2+=['--with','Container','(','FactoryServer',')']
266         if 'SalomeAppEngine' in self.args['embedded']:
267             self.SCMD2+=['--with','SalomeAppEngine','(',')']
268
269         if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
270             self.SCMD2+=['CPP']
271         if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
272             raise Exception('Python containers no longer supported')
273         if self.args['gui']:
274             session_gui = True
275             if self.args.has_key('session_gui'):
276                 session_gui = self.args['session_gui']
277             if session_gui:
278                 self.SCMD2+=['GUI']
279                 if self.args['splash']:
280                     self.SCMD2+=['SPLASH']
281                     pass
282                 if self.args['study_hdf'] is not None:
283                     self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
284                     pass
285                 if simanStudyName(self.args):
286                     self.SCMD2+=['--siman-study=%s'%simanStudyName(self.args)]
287                     pass
288                 pass
289                 if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
290                     msg = json.dumps(self.args['pyscript'])
291                     self.SCMD2+=['--pyscript=%s'%(msg)]
292                     pass
293                 pass
294             pass
295         if self.args['noexcepthandler']:
296             self.SCMD2+=['noexcepthandler']
297         if self.args.has_key('user_config'):
298             self.SCMD2+=['--resources=%s'%self.args['user_config']]
299         if self.args.has_key('modules'):
300             list_modules = []
301             #keep only modules with GUI
302             for m in modules_list:
303               if m not in modules_root_dir:
304                 list_modules.insert(0,m)
305               else:
306                 fr1 = os.path.join(modules_root_dir[m],"share","salome","resources",m.lower(),"SalomeApp.xml")
307                 fr2 = os.path.join(modules_root_dir[m],"share","salome","resources","SalomeApp.xml")
308                 if os.path.exists(fr1) or os.path.exists(fr2):
309                   list_modules.insert(0,m)
310             list_modules.reverse()
311             self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
312             pass
313         pass
314
315     def setpath(self,modules_list,modules_root_dir):
316         list_modules = modules_list[:]
317         list_modules.reverse()
318         if self.args["gui"] :
319             list_modules = ["KERNEL", "GUI"] + list_modules
320         else :
321             list_modules = ["KERNEL"] + list_modules
322
323         cata_path=get_cata_path(list_modules,modules_root_dir)
324
325         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
326             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
327             self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
328         else:
329             self.CMD=self.SCMD1 + self.SCMD2
330         if self.args.has_key('test'):
331             self.CMD+=['-test'] + self.args['test']
332         elif self.args.has_key('play'):
333             self.CMD+=['-play'] + self.args['play']
334
335         if self.args["gdb_session"] or self.args["ddd_session"]:
336             f = open(".gdbinit4salome", "w")
337             f.write("set args ")
338             args = " ".join(self.CMD[1:])
339             args = args.replace("(", "\(")
340             args = args.replace(")", "\)")
341             f.write(args)
342             f.write("\n")
343             f.close()
344             if self.args["ddd_session"]:
345                 self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
346             elif self.args["gdb_session"]:
347                 self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
348                 pass
349             pass
350
351         if self.args["valgrind_session"]:
352             l = ["valgrind"]
353             val = os.getenv("VALGRIND_OPTIONS")
354             if val:
355                 l += val.split()
356                 pass
357             self.CMD = l + self.CMD
358             pass
359
360 # ---
361
362 class LauncherServer(Server):
363     def __init__(self,args):
364         self.args=args
365         self.initArgs()
366         self.SCMD1=['SALOME_LauncherServer']
367         self.SCMD2=[]
368         if args["gui"] :
369             if 'registry' in self.args['embedded']:
370                 self.SCMD1+=['--with','Registry',
371                              '(','--salome_session','theSession',')']
372             if 'moduleCatalog' in self.args['embedded']:
373                 self.SCMD1+=['--with','ModuleCatalog','(','-common']
374                 self.SCMD2+=['-personal',
375                              '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
376             if 'study' in self.args['embedded']:
377                 self.SCMD2+=['--with','SALOMEDS','(',')']
378             if 'cppContainer' in self.args['embedded']:
379                 self.SCMD2+=['--with','Container','(','FactoryServer',')']
380
381     def setpath(self,modules_list,modules_root_dir):
382         list_modules = modules_list[:]
383         list_modules.reverse()
384         if self.args["gui"] :
385             list_modules = ["KERNEL", "GUI"] + list_modules
386         else :
387             list_modules = ["KERNEL"] + list_modules
388
389         cata_path=get_cata_path(list_modules,modules_root_dir)
390
391         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
392             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
393             self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
394         else:
395             self.CMD=self.SCMD1 + self.SCMD2
396
397 class NotifyServer(Server):
398     def __init__(self,args,modules_root_dir):
399         self.args=args
400         self.initArgs()
401         self.modules_root_dir=modules_root_dir
402         myLogName = os.environ["LOGNAME"]
403         self.CMD=['notifd','-c',
404                   self.modules_root_dir["KERNEL"] +'/share/salome/resources/kernel/channel.cfg',
405                   '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
406                   '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
407                   '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
408                   '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
409                   ]
410
411 #
412 # -----------------------------------------------------------------------------
413
414 def startGUI(clt):
415     """Salome Session Graphic User Interface activation"""
416     import Engines
417     import SALOME
418     import SALOMEDS
419     import SALOME_ModuleCatalog
420     import SALOME_Session_idl
421     session=clt.waitNS("/Kernel/Session",SALOME.Session)
422     session.GetInterface()
423
424 # -----------------------------------------------------------------------------
425
426 def startSalome(args, modules_list, modules_root_dir):
427     """Launch all SALOME servers requested by args"""
428     init_time = os.times()
429
430     if verbose(): print "startSalome ", args
431
432     #
433     # Set server launch command
434     #
435     if args.has_key('server_launch_mode'):
436         Server.set_server_launch_mode(args['server_launch_mode'])
437
438     #
439     # Wake up session option
440     #
441     if args['wake_up_session']:
442         if "OMNIORB_CONFIG" not in os.environ:
443             from salome_utils import generateFileName
444             omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
445             kwargs={}
446             if omniorbUserPath is not None:
447                 kwargs["with_username"]=True
448
449             last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
450                                                    suffix="last",
451                                                    extension="cfg",
452                                                    hidden=True,
453                                                    **kwargs)
454             os.environ['OMNIORB_CONFIG'] = last_running_config
455             pass
456         pass
457
458     #
459     # Initialisation ORB and Naming Service
460     #
461
462     clt=orbmodule.client(args)
463
464     #
465     # Wake up session option
466     #
467     if args['wake_up_session']:
468         import Engines
469         import SALOME
470         import SALOMEDS
471         import SALOME_ModuleCatalog
472         import SALOME_Session_idl
473         session = clt.waitNS("/Kernel/Session",SALOME.Session)
474         status = session.GetStatSession()
475         if status.activeGUI:
476             from salome_utils import getPortNumber
477             port = getPortNumber()
478             msg  = "Warning :"
479             msg += "\n"
480             msg += "Session GUI for port number %s is already active."%(port)
481             msg += "\n"
482             msg += "If you which to wake up another session,"
483             msg += "\n"
484             msg += "please use variable OMNIORB_CONFIG"
485             msg += "\n"
486             msg += "to get the correct session object in naming service."
487             sys.stdout.write(msg+"\n")
488             sys.stdout.flush()
489             return clt
490         session.GetInterface()
491         args["session_object"] = session
492         return clt
493
494     # Save Naming service port name into
495     # the file args["ns_port_log_file"]
496     if args.has_key('ns_port_log_file'):
497       omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
498       file_name = os.path.join(omniorbUserPath, args["ns_port_log_file"])
499       f = open(file_name, "w")
500       f.write(os.environ['NSPORT'])
501       f.close()
502
503     # Launch Logger Server (optional)
504     # and wait until it is registered in naming service
505     #
506
507     if args['logger']:
508         myServer=LoggerServer(args)
509         myServer.run()
510         clt.waitLogger("Logger")
511
512     # Notify Server launch
513     #
514
515     if sys.platform != "win32":
516       if verbose(): print "Notify Server to launch"
517
518       myServer=NotifyServer(args,modules_root_dir)
519       myServer.run()
520
521     # set siman python path before the session server launching to import scripts inside python console
522     if simanStudyName(args):
523         # MPV: use os.environ here because session server is launched in separated process and sys.path is missed in this case
524         os.environ["PYTHONPATH"] = "/tmp/SimanSalome/" + args['siman_study'] + "/" + \
525                                    args['siman_scenario'] + "/" + args['siman_user'] + os.pathsep + os.environ["PYTHONPATH"];
526
527     # Launch  Session Server (to show splash ASAP)
528     #
529
530     if args["gui"]:
531         mySessionServ = SessionServer(args,args['modules'],modules_root_dir)
532         mySessionServ.setpath(modules_list,modules_root_dir)
533         mySessionServ.run()
534
535     #
536     # Launch Registry Server,
537     # and wait until it is registered in naming service
538     #
539
540     if ('registry' not in args['embedded']) | (args["gui"] == 0) :
541         myServer=RegistryServer(args)
542         myServer.run()
543         if sys.platform == "win32":
544           clt.waitNS("/Registry")
545         else:
546           clt.waitNSPID("/Registry",myServer.PID)
547
548     #
549     # Launch Catalog Server,
550     # and wait until it is registered in naming service
551     #
552
553     if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
554         cataServer=CatalogServer(args)
555         cataServer.setpath(modules_list,modules_root_dir)
556         cataServer.run()
557         import SALOME_ModuleCatalog
558         if sys.platform == "win32":
559           clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
560         else:
561           clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
562
563     #
564     # Launch SalomeDS Server,
565     # and wait until it is registered in naming service
566     #
567
568     #print "ARGS = ",args
569     if ('study' not in args['embedded']) | (args["gui"] == 0):
570         print "RunStudy"
571         myServer=SalomeDSServer(args)
572         myServer.run()
573         if sys.platform == "win32":
574           clt.waitNS("/myStudyManager")
575         else:
576           clt.waitNSPID("/myStudyManager",myServer.PID)
577
578     #
579     # Launch LauncherServer
580     #
581
582     myCmServer = LauncherServer(args)
583     myCmServer.setpath(modules_list,modules_root_dir)
584     myCmServer.run()
585
586     #
587     # Launch ConnectionManagerServer
588     #
589
590     myConnectionServer = ConnectionManagerServer(args)
591     myConnectionServer.run()
592
593
594     from Utils_Identity import getShortHostName
595
596     if os.getenv("HOSTNAME") == None:
597         if os.getenv("HOST") == None:
598             os.environ["HOSTNAME"]=getShortHostName()
599         else:
600             os.environ["HOSTNAME"]=os.getenv("HOST")
601
602     theComputer = getShortHostName()
603
604     #
605     # Launch local C++ Container (FactoryServer),
606     # and wait until it is registered in naming service
607     #
608
609     if ('cppContainer' in args['standalone']) | (args["gui"] == 0) :
610         myServer=ContainerCPPServer(args)
611         myServer.run()
612         if sys.platform == "win32":
613           clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
614         else:
615           clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
616
617     #
618     # Launch local Python Container (FactoryServerPy),
619     # and wait until it is registered in naming service
620     #
621
622     if 'pyContainer' in args['standalone']:
623         raise Exception('Python containers no longer supported')
624
625     #
626     # Wait until Session Server is registered in naming service
627     #
628
629     if args["gui"]:
630 ##----------------
631         import Engines
632         import SALOME
633         import SALOMEDS
634         import SALOME_ModuleCatalog
635         import SALOME_Session_idl
636         if sys.platform == "win32":
637           session=clt.waitNS("/Kernel/Session",SALOME.Session)
638         else:
639           session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
640         args["session_object"] = session
641     end_time = os.times()
642     if verbose(): print
643     print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
644                                                          - init_time[4])
645
646     # ASV start GUI without Loader
647     #if args['gui']:
648     #    session.GetInterface()
649
650     #
651     # additionnal external python interpreters
652     #
653     nbaddi=0
654
655     try:
656         if 'interp' in args:
657             nbaddi = args['interp']
658     except:
659         import traceback
660         traceback.print_exc()
661         print "-------------------------------------------------------------"
662         print "-- to get an external python interpreter:runSalome --interp=1"
663         print "-------------------------------------------------------------"
664
665     if verbose(): print "additional external python interpreters: ", nbaddi
666     if nbaddi:
667         for i in range(nbaddi):
668             print "i=",i
669             anInterp=InterpServer(args)
670             anInterp.run()
671
672     # set PYTHONINSPECT variable (python interpreter in interactive mode)
673     if args['pinter']:
674         os.environ["PYTHONINSPECT"]="1"
675         try:
676             import readline
677         except ImportError:
678             pass
679
680     # siman session paramenters and checkout processing
681     if simanStudyName(args):
682         print '**********************************************'
683         print "Siman study name= '" + simanStudyName(args) + "'"
684         import SALOMEDS
685         obj = clt.Resolve('myStudyManager')
686         myStudyManager = obj._narrow(SALOMEDS.StudyManager)
687         aNewStudy = myStudyManager.NewStudy(simanStudyName(args))
688         aSimS = myStudyManager.GetSimanStudy()
689         aSimS._set_StudyId(args['siman_study'])
690         aSimS._set_ScenarioId(args['siman_scenario'])
691         aSimS._set_UserId(args['siman_user'])
692         aSimS.CheckOut(aNewStudy)
693         # if session server is enabled, activate the created study
694         if args["gui"]:
695             print "Activate the SIMAN study in the SALOME GUI"
696             obj = clt.Resolve('/Kernel/Session')
697             mySession = obj._narrow(SALOME.Session)
698             mySession.emitMessage("simanCheckoutDone " + simanStudyName(args))
699         print '**********************************************'
700
701     return clt
702
703 # -----------------------------------------------------------------------------
704
705 def useSalome(args, modules_list, modules_root_dir):
706     """
707     Launch all SALOME servers requested by args,
708     save list of process, give info to user,
709     show registered objects in Naming Service.
710     """
711     global process_id
712
713     clt=None
714     try:
715         clt = startSalome(args, modules_list, modules_root_dir)
716     except:
717         import traceback
718         traceback.print_exc()
719         print
720         print
721         print "--- Error during Salome launch ---"
722
723     #print process_id
724
725     from addToKillList import addToKillList
726     from killSalomeWithPort import getPiDict
727
728     filedict = getPiDict(args['port'])
729     for pid, cmd in process_id.items():
730         addToKillList(pid, cmd, args['port'])
731         pass
732
733     if verbose(): print """
734     Saving of the dictionary of Salome processes in %s
735     To kill SALOME processes from a console (kill all sessions from all ports):
736       python killSalome.py
737     To kill SALOME from the present interpreter, if it is not closed :
738       killLocalPort()      --> kill this session
739                                (use CORBA port from args of runSalome)
740       givenPortKill(port)  --> kill a specific session with given CORBA port
741       killAllPorts()       --> kill all sessions
742
743     runSalome, with --killall option, starts with killing
744     the processes resulting from the previous execution.
745     """%filedict
746
747     #
748     #  Print Naming Service directory list
749     #
750
751     if clt != None:
752         if verbose():
753             print
754             print " --- registered objects tree in Naming Service ---"
755             clt.showNS()
756             pass
757
758         if not args['gui'] or not args['session_gui']:
759             if args['shutdown_servers']:
760                 class __utils__(object):
761                     def __init__(self, port):
762                         self.port = port
763                         import killSalomeWithPort
764                         self.killSalomeWithPort = killSalomeWithPort
765                         return
766                     def __del__(self):
767                         self.killSalomeWithPort.killMyPort(self.port)
768                         return
769                     pass
770                 args['shutdown_servers'] = __utils__(args['port'])
771                 pass
772             pass
773
774         # run python scripts, passed as command line arguments
775         toimport = []
776         if args.has_key('pyscript'):
777             if args.has_key('gui') and args.has_key('session_gui'):
778                 if not args['gui'] or not args['session_gui']:
779                     toimport = args['pyscript']
780
781         from salomeLauncherUtils import formatScriptsAndArgs
782         command = formatScriptsAndArgs(toimport)
783         if command:
784             proc = subprocess.Popen(command, shell=True)
785             res = proc.wait()
786             if res: sys.exit(1) # if there's an error when executing script, we should explicitly exit
787
788     return clt
789
790 def execScript(script_path):
791     print 'executing', script_path
792     sys.path.insert(0, os.path.dirname(script_path))
793     execfile(script_path,globals())
794     del sys.path[0]
795
796 # -----------------------------------------------------------------------------
797
798 def registerEnv(args, modules_list, modules_root_dir):
799     """
800     Register args, modules_list, modules_root_dir in a file
801     for further use, when SALOME is launched embedded in an other application.
802     """
803     if sys.platform == "win32":
804       fileEnv = os.getenv('TEMP')
805     else:
806       fileEnv = '/tmp/'
807
808     fileEnv += os.getenv('USER') + "_" + str(args['port']) \
809             + '_' + args['appname'].upper() + '_env'
810     fenv=open(fileEnv,'w')
811     pickle.dump((args, modules_list, modules_root_dir),fenv)
812     fenv.close()
813     os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
814
815 # -----------------------------------------------------------------------------
816
817 def no_main():
818     """Salome Launch, when embedded in other application"""
819     fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
820     fenv=open(fileEnv,'r')
821     args, modules_list, modules_root_dir = pickle.load(fenv)
822     fenv.close()
823     kill_salome(args)
824     from searchFreePort import searchFreePort
825     searchFreePort(args, 0)
826     clt = useSalome(args, modules_list, modules_root_dir)
827     return clt
828
829 # -----------------------------------------------------------------------------
830
831 def main():
832     """Salome launch as a main application"""
833
834     # define folder to store omniorb config (initially in virtual application folder)
835     try:
836         from salomeLauncherUtils import setOmniOrbUserPath
837         setOmniOrbUserPath()
838     except Exception, e:
839         print e
840         sys.exit(1)
841
842     from salome_utils import getHostName
843     print "runSalome running on %s" % getHostName()
844     args, modules_list, modules_root_dir = setenv.get_config()
845
846     kill_salome(args)
847     save_config = True
848     if args.has_key('save_config'):
849         save_config = args['save_config']
850     # --
851     test = True
852     if args['wake_up_session']:
853         test = False
854         pass
855     if test:
856         from searchFreePort import searchFreePort
857         searchFreePort(args, save_config, args.get('useport'))
858         pass
859     # --
860     #setenv.main()
861     setenv.set_env(args, modules_list, modules_root_dir)
862     clt = useSalome(args, modules_list, modules_root_dir)
863     return clt,args
864
865 # -----------------------------------------------------------------------------
866
867 def foreGround(clt, args):
868     # --
869     if "session_object" not in args:
870         return
871     session = args["session_object"]
872     # --
873     # Wait until gui is arrived
874     # tmax = nbtot * dt
875     # --
876     gui_detected = False
877     dt = 0.1
878     nbtot = 100
879     nb = 0
880     while 1:
881         try:
882             status = session.GetStatSession()
883             gui_detected = status.activeGUI
884         except:
885             pass
886         if gui_detected:
887             break
888         from time import sleep
889         sleep(dt)
890         nb += 1
891         if nb == nbtot:
892             break
893         pass
894     # --
895     if not gui_detected:
896         return
897     # --
898     from salome_utils import getPortNumber
899     port = getPortNumber()
900     # --
901     server = Server({})
902     if sys.platform == "win32":
903       server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(os.getpid()), "%s"%(port)]
904     else:
905       server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(os.getpid()), "%s"%(port)]
906     server.run()
907     # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
908     # --
909     dt = 1.0
910     try:
911         while 1:
912             try:
913                 status = session.GetStatSession()
914                 assert status.activeGUI
915             except:
916                 break
917             from time import sleep
918             sleep(dt)
919             pass
920         pass
921     except KeyboardInterrupt:
922         from killSalomeWithPort import killMyPort
923         killMyPort(port)
924         pass
925     return
926 #
927
928 def runSalome():
929     import user
930     clt,args = main()
931     # --
932     test = args['gui'] and args['session_gui']
933     test = test or args['wake_up_session']
934     # --
935     # The next test covers the --pinter option or var PYTHONINSPECT setted
936     # --
937     test = test and not os.environ.get('PYTHONINSPECT')
938     # --
939     # The next test covers the python -i $KERNEL_ROOT_DIR/bin/salome/runSalome.py case
940     # --
941     try:
942         from ctypes import POINTER, c_int, cast, pythonapi
943         iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int))
944         test = test and not iflag_ptr.contents.value
945     except:
946         pass
947     # --
948     test = test and os.getenv("SALOME_TEST_MODE", "0") != "1"
949     test = test and args['foreground']
950     # --
951     if test:
952         foreGround(clt, args)
953         pass
954     # --
955     pass
956 #
957
958 # -----------------------------------------------------------------------------
959
960 if __name__ == "__main__":
961     runSalome()
962 #