Salome HOME
Merge branch 'V7_5_BR'
[modules/kernel.git] / bin / runSalome.py
index 676489e1fc68a767c66392553c4696e409c8149a..73a8b0df2037ff8f122adaf16decccb4dac15a82 100755 (executable)
@@ -1,6 +1,6 @@
 #!/usr/bin/env python
 #  -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
+# Copyright (C) 2007-2015  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
@@ -8,7 +8,7 @@
 # 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.
+# version 2.1 of the License, or (at your option) any later version.
 #
 # This library is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -32,8 +32,8 @@ import setenv
 from launchConfigureParser import verbose
 from server import process_id, Server
 import json
-from salomeLauncherUtils import formatScriptsAndArgs
 import subprocess
+from salomeContextUtils import ScriptAndArgsObjectEncoder
 
 # -----------------------------------------------------------------------------
 
@@ -223,10 +223,8 @@ class LoggerServer(Server):
     def __init__(self,args):
         self.args=args
         self.initArgs()
-        from salome_utils import generateFileName
-        if sys.platform == "win32": dirpath = os.environ["HOME"]
-        else:                       dirpath = "/tmp"
-        logfile = generateFileName( dirpath,
+        from salome_utils import generateFileName, getLogDir
+        logfile = generateFileName( getLogDir(),
                                     prefix="logger",
                                     extension="log",
                                     with_username=True,
@@ -288,7 +286,7 @@ class SessionServer(Server):
                     pass
                 pass
                 if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
-                    msg = json.dumps(self.args['pyscript'])
+                    msg = json.dumps(self.args['pyscript'], cls=ScriptAndArgsObjectEncoder)
                     self.SCMD2+=['--pyscript=%s'%(msg)]
                     pass
                 pass
@@ -394,21 +392,6 @@ class LauncherServer(Server):
             self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
         else:
             self.CMD=self.SCMD1 + self.SCMD2
-
-class NotifyServer(Server):
-    def __init__(self,args,modules_root_dir):
-        self.args=args
-        self.initArgs()
-        self.modules_root_dir=modules_root_dir
-        myLogName = os.environ["LOGNAME"]
-        self.CMD=['notifd','-c',
-                  self.modules_root_dir["KERNEL"] +'/share/salome/resources/kernel/channel.cfg',
-                  '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
-                  '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
-                  '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
-                  '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
-                  ]
-
 #
 # -----------------------------------------------------------------------------
 
@@ -492,15 +475,6 @@ def startSalome(args, modules_list, modules_root_dir):
         args["session_object"] = session
         return clt
 
-    # Save Naming service port name into
-    # the file args["ns_port_log_file"]
-    if args.has_key('ns_port_log_file'):
-      omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
-      file_name = os.path.join(omniorbUserPath, args["ns_port_log_file"])
-      f = open(file_name, "w")
-      f.write(os.environ['NSPORT'])
-      f.close()
-
     # Launch Logger Server (optional)
     # and wait until it is registered in naming service
     #
@@ -510,20 +484,13 @@ def startSalome(args, modules_list, modules_root_dir):
         myServer.run()
         clt.waitLogger("Logger")
 
-    # Notify Server launch
-    #
-
-    if sys.platform != "win32":
-      if verbose(): print "Notify Server to launch"
-
-      myServer=NotifyServer(args,modules_root_dir)
-      myServer.run()
-
     # set siman python path before the session server launching to import scripts inside python console
     if simanStudyName(args):
         # MPV: use os.environ here because session server is launched in separated process and sys.path is missed in this case
-        os.environ["PYTHONPATH"] = "/tmp/SimanSalome/" + args['siman_study'] + "/" + \
-                                   args['siman_scenario'] + "/" + args['siman_user'] + os.pathsep + os.environ["PYTHONPATH"];
+        from salome_utils import getTmpDir
+        ppath = os.path.join(getTmpDir, "SimanSalome", args['siman_study'],
+                             args['siman_scenario'], args['siman_user'])
+        os.environ["PYTHONPATH"] = ppath + os.pathsep + os.environ["PYTHONPATH"]
 
     # Launch  Session Server (to show splash ASAP)
     #
@@ -615,11 +582,6 @@ def startSalome(args, modules_list, modules_root_dir):
         else:
           clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
 
-    #
-    # Launch local Python Container (FactoryServerPy),
-    # and wait until it is registered in naming service
-    #
-
     if 'pyContainer' in args['standalone']:
         raise Exception('Python containers no longer supported')
 
@@ -677,7 +639,7 @@ def startSalome(args, modules_list, modules_root_dir):
             import readline
         except ImportError:
             pass
-    
+
     # siman session paramenters and checkout processing
     if simanStudyName(args):
         print '**********************************************'
@@ -698,7 +660,7 @@ def startSalome(args, modules_list, modules_root_dir):
             mySession = obj._narrow(SALOME.Session)
             mySession.emitMessage("simanCheckoutDone " + simanStudyName(args))
         print '**********************************************'
-        
+
     return clt
 
 # -----------------------------------------------------------------------------
@@ -768,27 +730,37 @@ def useSalome(args, modules_list, modules_root_dir):
                         self.killSalomeWithPort.killMyPort(self.port)
                         return
                     pass
-                args['shutdown_servers'] = __utils__(args['port'])
+                def func(s):
+                    del s
+                import atexit
+                atexit.register(func, __utils__(args['port']))
                 pass
             pass
 
         # run python scripts, passed as command line arguments
         toimport = []
-        if args.has_key('pyscript'):
-            if args.has_key('gui') and args.has_key('session_gui'):
-                if not args['gui'] or not args['session_gui']:
+        if args.has_key('gui') and args.has_key('session_gui'):
+            if not args['gui'] or not args['session_gui']:
+                if args.has_key('study_hdf'):
+                    toopen = args['study_hdf']
+                    if toopen:
+                        import salome
+                        salome.salome_init(toopen)
+                if args.has_key('pyscript'):
                     toimport = args['pyscript']
-
+        from salomeContextUtils import formatScriptsAndArgs
         command = formatScriptsAndArgs(toimport)
         if command:
             proc = subprocess.Popen(command, shell=True)
-            proc.wait()
+            addToKillList(proc.pid, command, args['port'])
+            res = proc.wait()
+            if res: sys.exit(1) # if there's an error when executing script, we should explicitly exit
 
     return clt
 
 def execScript(script_path):
     print 'executing', script_path
-    sys.path.insert(0, os.path.dirname(script_path))
+    sys.path.insert(0, os.path.realpath(os.path.dirname(script_path)))
     execfile(script_path,globals())
     del sys.path[0]
 
@@ -799,11 +771,8 @@ def registerEnv(args, modules_list, modules_root_dir):
     Register args, modules_list, modules_root_dir in a file
     for further use, when SALOME is launched embedded in an other application.
     """
-    if sys.platform == "win32":
-      fileEnv = os.getenv('TEMP')
-    else:
-      fileEnv = '/tmp/'
-
+    from salome_utils import getTmpDir
+    fileEnv = getTmpDir()
     fileEnv += os.getenv('USER') + "_" + str(args['port']) \
             + '_' + args['appname'].upper() + '_env'
     fenv=open(fileEnv,'w')
@@ -830,20 +799,17 @@ def no_main():
 def main():
     """Salome launch as a main application"""
 
-    ### TEMP >>> ###
-    if not os.getenv("OMNIORB_USER_PATH"):
-        homePath = os.path.realpath(os.path.expanduser('~'))
-        #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
-        defaultOmniorbUserPath = homePath
-        if os.getenv("APPLI"):
-            defaultOmniorbUserPath = os.path.join(homePath, os.getenv("APPLI"), "USERS")
-        os.environ["OMNIORB_USER_PATH"] = defaultOmniorbUserPath
-        pass
-    ### <<< TEMP ###
+    # define folder to store omniorb config (initially in virtual application folder)
+    try:
+        from salomeContextUtils import setOmniOrbUserPath
+        setOmniOrbUserPath()
+    except Exception, e:
+        print e
+        sys.exit(1)
 
     from salome_utils import getHostName
-    print "runSalome running on %s" % getHostName()
     args, modules_list, modules_root_dir = setenv.get_config()
+    print "runSalome running on %s" % getHostName()
 
     kill_salome(args)
     save_config = True
@@ -953,7 +919,6 @@ def runSalome():
     if test:
         foreGround(clt, args)
         pass
-    # --
     pass
 #