Salome HOME
tag 5.1.2 --> 5.1.3
[modules/kernel.git] / bin / runSalome.py
index f20b507944fefc072e52db5d699c029baa45c428..d67d6b0571ad2e423801852643ef7af4ba378cee 100755 (executable)
@@ -1,30 +1,37 @@
 #!/usr/bin/env python
+#  -*- coding: iso-8859-1 -*-
+#  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
+#
+#  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+#  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+#
+#  This library is free software; you can redistribute it and/or
+#  modify it under the terms of the GNU Lesser General Public
+#  License as published by the Free Software Foundation; either
+#  version 2.1 of the License.
+#
+#  This library is distributed in the hope that it will be useful,
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#  Lesser General Public License for more details.
+#
+#  You should have received a copy of the GNU Lesser General Public
+#  License along with this library; if not, write to the Free Software
+#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+#
+#  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+## @package runSalome
+# \brief Module that provides services to launch SALOME
+#
+#
 
-# Copyright (C) 2005  OPEN CASCADE, CEA, EDF R&D, LEG
-#           PRINCIPIA R&D, EADS CCR, Lip6, BV, CEDRAT
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either 
-# version 2.1 of the License.
-# 
-# This library is distributed in the hope that it will be useful 
-# but WITHOUT ANY WARRANTY; without even the implied warranty of 
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
-# Lesser General Public License for more details.
-# 
-# You should have received a copy of the GNU Lesser General Public  
-# License along with this library; if not, write to the Free Software 
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
-# 
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-# 
-
-import sys, os, string, glob, time, pickle
+import sys, os, string, glob, time, pickle, re
 import orbmodule
 import setenv
 from server import *
 from launchConfigureParser import verbose
-#process_id = {} move to server.py
+from server import process_id
 
 # -----------------------------------------------------------------------------
 
@@ -74,7 +81,7 @@ def kill_salome(args):
 
 # -----------------------------------------------------------------------------
 #
-# Definition des classes d'objets pour le lancement des Server CORBA
+# Class definitions to launch CORBA Servers
 #
 
 class InterpServer(Server):
@@ -82,7 +89,6 @@ class InterpServer(Server):
         self.args=args
         env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
         self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
-        #self.CMD=['xterm', '-e', 'python']
        
     def run(self):
         global process_id
@@ -189,25 +195,26 @@ class ContainerPYServer(Server):
 
 # ---
 
-class ContainerSUPERVServer(Server):
-    def __init__(self,args):
-        self.args=args
-        self.initArgs()
-   #  if sys.platform == "win32":
-#          self.CMD=[os.environ["KERNEL_ROOT_DIR"] + "/win32/" + os.environ["BIN_ENV"] + "/" + 'SALOME_Container' + ".exe",'SuperVisionContainer']
-# else:
-        self.CMD=['SALOME_Container','SuperVisionContainer']
-
-# ---
-
 class LoggerServer(Server):
     def __init__(self,args):
         self.args=args
         self.initArgs()
-        if sys.platform == "win32":
-            self.CMD=['SALOME_Logger_Server', os.environ["HOME"] + "/logger.log"];
-        else:
-            self.CMD=['SALOME_Logger_Server', 'logger.log']
+        from salome_utils import generateFileName
+        if sys.platform == "win32": dirpath = os.environ["HOME"]
+        else:                       dirpath = "/tmp"
+        logfile = generateFileName( dirpath,
+                                    prefix="logger",
+                                    extension="log",
+                                    with_username=True,
+                                    with_hostname=True,
+                                    with_port=True)
+        print "==========================================================="
+        print "Logger server: put log to the file:"
+        print logfile
+        print "==========================================================="
+        self.CMD=['SALOME_Logger_Server', logfile]
+        pass
+    pass # end of LoggerServer class
 
 # ---
 
@@ -240,8 +247,6 @@ class SessionServer(Server):
             self.SCMD2+=['CPP']
         if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
             self.SCMD2+=['PY']
-        if 'supervContainer' in self.args['standalone']:
-            self.SCMD2+=['SUPERV']
         if self.args['gui']:
             session_gui = True
             if self.args.has_key('session_gui'):
@@ -297,7 +302,27 @@ class SessionServer(Server):
             self.CMD=self.SCMD1 + ['\"' + string.join(cata_path,'\"::\"') + '\"'] + self.SCMD2
         else:
             self.CMD=self.SCMD1 + self.SCMD2
-      
+        if self.args.has_key('test'):
+            self.CMD+=['-test'] + self.args['test']
+        elif self.args.has_key('play'):
+            self.CMD+=['-play'] + self.args['play']
+
+        if self.args["gdb_session"] or self.args["ddd_session"]:
+            f = open(".gdbinit4salome", "w")
+            f.write("set args ")
+            args = " ".join(self.CMD[1:])
+            args = args.replace("(", "\(")
+            args = args.replace(")", "\)")
+            f.write(args)
+            f.write("\n")
+            f.close()
+            if self.args["ddd_session"]:
+                self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
+            elif self.args["gdb_session"]:
+                self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
+                pass
+            pass
+        
 # ---
 
 class LauncherServer(Server):
@@ -373,9 +398,6 @@ def startGUI():
     import SALOME
     import SALOMEDS
     import SALOME_ModuleCatalog
-    reload(Engines)
-    reload(SALOME)
-    reload(SALOMEDS)
     import SALOME_Session_idl
     session=clt.waitNS("/Kernel/Session",SALOME.Session)
     session.GetInterface()
@@ -389,7 +411,7 @@ def startSalome(args, modules_list, modules_root_dir):
     if verbose(): print "startSalome ", args
     
     #
-    # Initialisation ORB et Naming Service
+    # Initialisation ORB and Naming Service
     #
    
     clt=orbmodule.client(args)
@@ -406,8 +428,8 @@ def startSalome(args, modules_list, modules_root_dir):
       f.write(os.environ['NSPORT'])
       f.close()
 
-    # (non obligatoire) Lancement Logger Server
-    # et attente de sa disponibilite dans le naming service
+    # Launch Logger Server (optional)
+    # and wait until it is registered in naming service
     #
 
     if args['logger']:
@@ -418,15 +440,13 @@ def startSalome(args, modules_list, modules_root_dir):
     # Notify Server launch
     #
 
-    if verbose(): print "Notify Server to launch"
-
     if sys.platform != "win32":
-      print "Notify Server to launch"
+      if verbose(): print "Notify Server to launch"
     
       myServer=NotifyServer(args,modules_root_dir)
       myServer.run()
 
-    # Lancement Session Server (to show splash ASAP)
+    # Launch  Session Server (to show splash ASAP)
     #
 
     if args["gui"]:
@@ -435,8 +455,8 @@ def startSalome(args, modules_list, modules_root_dir):
         mySessionServ.run()
 
     #
-    # Lancement Registry Server,
-    # attente de la disponibilite du Registry dans le Naming Service
+    # Launch Registry Server,
+    # and wait until it is registered in naming service
     #
 
     if ('registry' not in args['embedded']) | (args["gui"] == 0) :
@@ -448,10 +468,9 @@ def startSalome(args, modules_list, modules_root_dir):
           clt.waitNSPID("/Registry",myServer.PID)
 
     #
-    # Lancement Catalog Server,
-    # attente de la disponibilite du Catalog Server dans le Naming Service
+    # Launch Catalog Server,
+    # and wait until it is registered in naming service
     #
-    
 
     if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
         cataServer=CatalogServer(args)
@@ -464,8 +483,8 @@ def startSalome(args, modules_list, modules_root_dir):
           clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
 
     #
-    # Lancement SalomeDS Server,
-    # attente de la disponibilite du SalomeDS dans le Naming Service
+    # Launch SalomeDS Server,
+    # and wait until it is registered in naming service
     #
 
     #print "ARGS = ",args
@@ -479,7 +498,7 @@ def startSalome(args, modules_list, modules_root_dir):
           clt.waitNSPID("/myStudyManager",myServer.PID)
 
     #
-    # Lancement LauncherServer
+    # Launch LauncherServer
     #
     
     myCmServer = LauncherServer(args)
@@ -505,8 +524,8 @@ def startSalome(args, modules_list, modules_root_dir):
     theComputer = getShortHostName()
     
     #
-    # Lancement Container C++ local,
-    # attente de la disponibilite du Container C++ local dans le Naming Service
+    # Launch local C++ Container (FactoryServer),
+    # and wait until it is registered in naming service
     #
 
     if ('cppContainer' in args['standalone']) | (args["gui"] == 0) : 
@@ -518,9 +537,8 @@ def startSalome(args, modules_list, modules_root_dir):
           clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
 
     #
-    # Lancement Container Python local,
-    # attente de la disponibilite du Container Python local
-    # dans le Naming Service
+    # Launch local Python Container (FactoryServerPy),
+    # and wait until it is registered in naming service
     #
 
     if 'pyContainer' in args['standalone']:
@@ -532,21 +550,7 @@ def startSalome(args, modules_list, modules_root_dir):
           clt.waitNSPID("/Containers/" + theComputer + "/FactoryServerPy",myServer.PID)
 
     #
-    # Lancement Container Supervision local,
-    # attente de la disponibilite du Container Supervision local
-    # dans le Naming Service
-    #
-
-    if 'supervContainer' in args['standalone']:
-        myServer=ContainerSUPERVServer(args)
-        myServer.run()
-        if sys.platform == "win32":
-          clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
-        else:
-          clt.waitNSPID("/Containers/" + theComputer + "/SuperVisionContainer",myServer.PID)
-  
-    #
-    # Attente de la disponibilite du Session Server dans le Naming Service
+    # Wait until Session Server is registered in naming service
     #
     
     if args["gui"]:
@@ -555,9 +559,6 @@ def startSalome(args, modules_list, modules_root_dir):
         import SALOME
         import SALOMEDS
         import SALOME_ModuleCatalog
-        reload(Engines)
-        reload(SALOME)
-        reload(SALOMEDS)
         import SALOME_Session_idl
         if sys.platform == "win32":
           session=clt.waitNS("/Kernel/Session",SALOME.Session)
@@ -594,9 +595,10 @@ def startSalome(args, modules_list, modules_root_dir):
             anInterp=InterpServer(args)
             anInterp.run()
 
-    # set PYTHONINSPECT variable
+    # set PYTHONINSPECT variable (python interpreter in interactive mode)
     if args['pinter']:
         os.environ["PYTHONINSPECT"]="1"
+        import readline
         
     return clt
 
@@ -622,22 +624,14 @@ def useSalome(args, modules_list, modules_root_dir):
         
     #print process_id
 
+    from addToKillList import addToKillList
     from killSalomeWithPort import getPiDict
-    filedict = getPiDict(args['port'])
 
-    process_ids = []
-    try:
-        fpid=open(filedict, 'r')
-        process_ids=pickle.load(fpid)
-        fpid.close()
-    except:
+    filedict = getPiDict(args['port'])
+    for pid, cmd in process_id.items():
+        addToKillList(pid, cmd, args['port'])
         pass
-    
-    fpid=open(filedict, 'w')
-    process_ids.append(process_id)
-    pickle.dump(process_ids,fpid)
-    fpid.close()
-    
+
     if verbose(): print """
     Saving of the dictionary of Salome processes in %s
     To kill SALOME processes from a console (kill all sessions from all ports):
@@ -653,7 +647,7 @@ def useSalome(args, modules_list, modules_root_dir):
     """%filedict
     
     #
-    #  Impression arborescence Naming Service
+    #  Print Naming Service directory list
     #
     
     if clt != None:
@@ -663,6 +657,22 @@ def useSalome(args, modules_list, modules_root_dir):
             clt.showNS()
             pass
         
+        if not args['gui'] or not args['session_gui']:
+            if args['shutdown_servers']:
+                class __utils__(object):
+                    def __init__(self, port):
+                        self.port = port
+                        import killSalomeWithPort
+                        self.killSalomeWithPort = killSalomeWithPort
+                        return
+                    def __del__(self):
+                        self.killSalomeWithPort.killMyPort(self.port)
+                        return
+                    pass
+                args['shutdown_servers'] = __utils__(args['port'])
+                pass
+            pass
+        
         # run python scripts, passed via --execute option
         toimport = []
         if args.has_key('pyscript'):
@@ -674,14 +684,14 @@ def useSalome(args, modules_list, modules_root_dir):
             if toimport[ i ] == 'killall':
                 clt.showNS()
                 killAllPorts()
-                import sys
                 sys.exit(0)
             else:
                 scrname = toimport[ i ]
                 if len(scrname) > 2 and (len(scrname) - string.rfind(scrname, ".py") == 3):
                     print 'executing',scrname
-                    doexec = 'execfile(\"%s\")'%scrname
-                    exec doexec
+                    sys.path.insert( 0, os.path.dirname(scrname))
+                    execfile(scrname,globals())
+                    del sys.path[0]
                 else:
                     print 'importing',scrname
                     doimport = 'import ' + scrname
@@ -713,96 +723,104 @@ def registerEnv(args, modules_list, modules_root_dir):
 
 def searchFreePort(args, save_config=1):
     print "Searching for a free port for naming service:",
+    #
+    if sys.platform == "win32":
+        tmp_file = os.getenv('TEMP');
+    else:
+        tmp_file = '/tmp'
+    tmp_file = os.path.join(tmp_file, '.netstat_%s'%os.getpid())
+    #
+    ###status = os.system("netstat -ltn | grep -E :%s > /dev/null 2>&1"%(NSPORT))
+    os.system( "netstat -a -n > %s" % tmp_file );
+    f = open( tmp_file, 'r' );
+    ports = f.readlines();
+    f.close();
+    os.remove( tmp_file );
+    #
+    def portIsUsed(port, data):
+        regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
+        for item in data:
+            try:
+                p = int(regObj.match(item).group(1))
+                if p == port: return True
+                pass
+            except:
+                pass
+            pass
+        return False
+    #
     NSPORT=2810
-    limit=NSPORT
-    limit=limit+10
+    limit=NSPORT+100
+    #
     while 1:
-        import os
-        import re
-        from os import getpid
-        from os import system
-
-        if sys.platform == "win32":
-            tmp_file = os.getenv('TEMP');
-        else:
-            tmp_file = '/tmp/'
-        tmp_file += 'hostname_%s'%(getpid())
-
-#       status = os.system("netstat -ltn | grep -E :%s > /dev/null 2>&1"%(NSPORT))
-
-        system( "netstat -a -n > %s" % tmp_file );
-
-        f = open( tmp_file, 'r' );
-        lines = f.readlines();
-        f.close();
-
-        pattern = "tcp.*:([0-9]+).*:.*listen";
-        regObj = re.compile( pattern, re.IGNORECASE );
-
-        status = 1;
-        for item in lines:
-            m = regObj.search( item )
-            if m:
-                try:
-                    p = int( m.group(1) )
-                    if p == NSPORT: 
-                        status = 0;
-                        break;
-                except:
-                    pass
-            pass
-
-        if status == 1:
+        if not portIsUsed(NSPORT, ports):
             print "%s - OK"%(NSPORT)
             #
-            system('hostname > %s'%(tmp_file))
-            f = open(tmp_file)
-            myhost = f.read()
-            myhost = myhost[:-1]
-            f.close()
-
-            os.remove( tmp_file );
-
+            from salome_utils import generateFileName, getHostName
+            hostname = getHostName()
             #
-            home = os.environ['HOME']
-            appli=os.environ.get("APPLI")
-            if appli is not None:
-                home='%s/%s'%(home,appli)
-                pass
+            home  = os.getenv("HOME")
+            appli = os.getenv("APPLI")
+            kwargs={}
+            if appli is not None: 
+              home = os.path.join(home, appli,"USERS")
+              kwargs["with_username"]=True
             #
-            os.environ['OMNIORB_CONFIG'] = '%s/.omniORB_%s_%s.cfg'%(home, myhost, NSPORT)
-            initref = "NameService=corbaname::%s:%s"%(myhost, NSPORT)
-            os.environ['NSPORT'] = "%s"%(NSPORT)
-            os.environ['NSHOST'] = "%s"%(myhost)
-            f = open(os.environ['OMNIORB_CONFIG'], "w")
-            import CORBA
+            omniorb_config = generateFileName(home, prefix="omniORB",
+                                              extension="cfg",
+                                              hidden=True,
+                                              with_hostname=True,
+                                              with_port=NSPORT,
+                                              **kwargs)
+            orbdata = []
+            initref = "NameService=corbaname::%s:%s"%(hostname, NSPORT)
+            from omniORB import CORBA
             if CORBA.ORB_ID == "omniORB4":
-                initref += "\ngiopMaxMsgSize = 2097152000  # 2 GBytes";
-                initref += "\ntraceLevel = 0 # critical errors only";
-                f.write("InitRef = %s\n"%(initref))
+                orbdata.append("InitRef = %s"%(initref))
+                orbdata.append("giopMaxMsgSize = 2097152000  # 2 GBytes")
+                orbdata.append("traceLevel = 0 # critical errors only")
             else:
-                initref += "\nORBgiopMaxMsgSize = 2097152000  # 2 GBytes";
-                initref += "\nORBtraceLevel = 0 # critical errors only";
-                f.write("ORBInitRef %s\n"%(initref))
+                orbdata.append("ORBInitRef %s"%(initref))
+                orbdata.append("ORBgiopMaxMsgSize = 2097152000  # 2 GBytes")
+                orbdata.append("ORBtraceLevel = 0 # critical errors only")
                 pass
+            orbdata.append("")
+            f = open(omniorb_config, "w")
+            f.write("\n".join(orbdata))
             f.close()
+            #
+            os.environ['OMNIORB_CONFIG'] = omniorb_config
+            os.environ['NSPORT'] = "%s"%(NSPORT)
+            os.environ['NSHOST'] = "%s"%(hostname)
             args['port'] = os.environ['NSPORT']
             #
             if save_config:
-                from os import system
-                if sys.platform == "win32":
-                    import shutil       
-                    shutil.copyfile( os.environ['OMNIORB_CONFIG'], "%s/.omniORB_last.cfg"%( home ) )
-                else:            
-                    system('ln -s -f %s %s/.omniORB_last.cfg'%(os.environ['OMNIORB_CONFIG'], home))     
-                pass
+                last_running_config = generateFileName(home, prefix="omniORB",
+                                                       suffix="last",
+                                                       extension="cfg",
+                                                       hidden=True,
+                                                       **kwargs)
+                try:
+                    if sys.platform == "win32":
+                        import shutil       
+                        shutil.copyfile(omniorb_config, last_running_config)
+                    else:
+                        try:
+                            os.remove(last_running_config)
+                        except OSError:
+                            pass
+                        os.symlink(omniorb_config, last_running_config)
+                        pass
+                    pass
+                except:
+                    pass
             break
         print "%s"%(NSPORT),
         if NSPORT == limit:
             msg  = "\n"
             msg += "Can't find a free port to launch omniNames\n"
             msg += "Try to kill the running servers and then launch SALOME again.\n"
-            raise msg
+            raise RuntimeError, msg
         NSPORT=NSPORT+1
         pass
     return
@@ -824,15 +842,16 @@ def no_main():
 
 def main():
     """Salome launch as a main application"""
-    import sys
-    print "runSalome running on ",os.getenv('HOSTNAME')
+    from salome_utils import getHostName
+    print "runSalome running on %s" % getHostName()
     args, modules_list, modules_root_dir = setenv.get_config()
     kill_salome(args)
     save_config = True
     if args.has_key('save_config'):
         save_config = args['save_config']
     searchFreePort(args, save_config)
-    setenv.main()
+    #setenv.main()
+    setenv.set_env(args, modules_list, modules_root_dir)
     clt = useSalome(args, modules_list, modules_root_dir)
     return clt,args