Salome HOME
rename salome runner/launcher as salome context
[modules/kernel.git] / bin / runSalome.py
index 44a9693da4f9c8278428d69387ce091c82c486f3..514bd07fc7339aa2061e6ce81ab584a29f4cb131 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-2014  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
@@ -31,6 +31,8 @@ import orbmodule
 import setenv
 from launchConfigureParser import verbose
 from server import process_id, Server
+import json
+import subprocess
 
 # -----------------------------------------------------------------------------
 
@@ -62,7 +64,7 @@ def givenPortKill(port):
     try:
         killMyPort(my_port)
     except:
-        print "problem in LocalPortKill(), killMyPort("<<port<<")"
+        print "problem in LocalPortKill(), killMyPort(%s)"%port
         pass
     pass
 
@@ -137,7 +139,28 @@ def get_cata_path(list_modules,modules_root_dir):
 
     return cata_path
 
-
+_siman_name = None
+def simanStudyName(args):
+    global _siman_name
+    if _siman_name is None:
+        # siman session paramenters and checkout processing
+        _siman_name = ""
+        if 'siman' in args:
+            siman_data = []
+            for param in [ 'study', 'scenario', 'user']:
+                siman_param = "siman_%s"%param
+                if siman_param in args:
+                    siman_data.append(args[siman_param])
+                else:
+                    print "SIMAN %s must be defined using parameter --siman-%s=XXX" % (siman_param, siman_param)
+                    pass
+                pass
+            if len(siman_data) == 3:
+                _siman_name = "_".join(siman_data)
+                pass
+            pass
+        pass
+    return _siman_name
 
 class CatalogServer(Server):
     def __init__(self,args):
@@ -259,9 +282,13 @@ class SessionServer(Server):
                 if self.args['study_hdf'] is not None:
                     self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
                     pass
+                if simanStudyName(self.args):
+                    self.SCMD2+=['--siman-study=%s'%simanStudyName(self.args)]
+                    pass
                 pass
                 if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
-                    self.SCMD2+=['--pyscript=%s'%(",".join(self.args['pyscript']))]
+                    msg = json.dumps(self.args['pyscript'])
+                    self.SCMD2+=['--pyscript=%s'%(msg)]
                     pass
                 pass
             pass
@@ -464,15 +491,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
     #
@@ -491,6 +509,12 @@ def startSalome(args, modules_list, modules_root_dir):
       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"];
+
     # Launch  Session Server (to show splash ASAP)
     #
 
@@ -581,11 +605,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')
 
@@ -644,6 +663,27 @@ def startSalome(args, modules_list, modules_root_dir):
         except ImportError:
             pass
 
+    # siman session paramenters and checkout processing
+    if simanStudyName(args):
+        print '**********************************************'
+        print "Siman study name= '" + simanStudyName(args) + "'"
+        import SALOMEDS
+        obj = clt.Resolve('myStudyManager')
+        myStudyManager = obj._narrow(SALOMEDS.StudyManager)
+        aNewStudy = myStudyManager.NewStudy(simanStudyName(args))
+        aSimS = myStudyManager.GetSimanStudy()
+        aSimS._set_StudyId(args['siman_study'])
+        aSimS._set_ScenarioId(args['siman_scenario'])
+        aSimS._set_UserId(args['siman_user'])
+        aSimS.CheckOut(aNewStudy)
+        # if session server is enabled, activate the created study
+        if args["gui"]:
+            print "Activate the SIMAN study in the SALOME GUI"
+            obj = clt.Resolve('/Kernel/Session')
+            mySession = obj._narrow(SALOME.Session)
+            mySession.emitMessage("simanCheckoutDone " + simanStudyName(args))
+        print '**********************************************'
+
     return clt
 
 # -----------------------------------------------------------------------------
@@ -709,7 +749,7 @@ def useSalome(args, modules_list, modules_root_dir):
                         import killSalomeWithPort
                         self.killSalomeWithPort = killSalomeWithPort
                         return
-                    def __del__(self):
+                    def delete(self):
                         self.killSalomeWithPort.killMyPort(self.port)
                         return
                     pass
@@ -717,46 +757,21 @@ def useSalome(args, modules_list, modules_root_dir):
                 pass
             pass
 
-        # run python scripts, passed via --execute option
+        # 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']:
                     toimport = args['pyscript']
 
-        for srcname in toimport :
-            if srcname == 'killall':
-                clt.showNS()
-                killAllPorts()
-                sys.exit(0)
-            else:
-                if os.path.isabs(srcname):
-                    if os.path.exists(srcname):
-                        execScript(srcname)
-                    elif os.path.exists(srcname+".py"):
-                        execScript(srcname+".py")
-                    else:
-                        print "Can't execute file %s" % srcname
-                    pass
-                else:
-                    found = False
-                    for path in [os.getcwd()] + sys.path:
-                        if os.path.exists(os.path.join(path,srcname)):
-                            execScript(os.path.join(path,srcname))
-                            found = True
-                            break
-                        elif os.path.exists(os.path.join(path,srcname+".py")):
-                            execScript(os.path.join(path,srcname+".py"))
-                            found = True
-                            break
-                        pass
-                    if not found:
-                        print "Can't execute file %s" % srcname
-                        pass
-                    pass
-                pass
-            pass
-        pass
+        from salomeContextUtils import formatScriptsAndArgs
+        command = formatScriptsAndArgs(toimport)
+        if command:
+            proc = subprocess.Popen(command, shell=True)
+            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):
@@ -796,12 +811,26 @@ def no_main():
     from searchFreePort import searchFreePort
     searchFreePort(args, 0)
     clt = useSalome(args, modules_list, modules_root_dir)
+
+    if args.has_key('shutdown_servers') :
+        var = args['shutdown_servers']
+        if hasattr(var, 'delete') and callable(getattr(var, 'delete')) :
+            var.delete()
     return clt
 
 # -----------------------------------------------------------------------------
 
 def main():
     """Salome launch as a main application"""
+
+    # 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()
@@ -915,22 +944,15 @@ def runSalome():
         foreGround(clt, args)
         pass
     # --
+    if args.has_key('shutdown_servers') :
+        var = args['shutdown_servers']
+        if hasattr(var, 'delete') and callable(getattr(var, 'delete')) :
+            var.delete()
     pass
 #
 
 # -----------------------------------------------------------------------------
 
 if __name__ == "__main__":
-
-    ### TEMP ###
-    homePath = os.path.realpath(os.path.expanduser('~'))
-    #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
-    appli = os.getenv("APPLI")
-    defaultOmniorbUserPath = homePath
-    if appli:
-        defaultOmniorbUserPath = os.path.join( homePath, appli, "USERS" )
-    os.environ["OMNIORB_USER_PATH"] = defaultOmniorbUserPath
-    ############
-
     runSalome()
 #