Salome HOME
Make the EDF non reg test work in SSL mode : Bug14551_reloadStudy.py
[modules/kernel.git] / src / KERNEL_PY / __init__.py
old mode 100755 (executable)
new mode 100644 (file)
index ce4a8d4..7b99a03
@@ -1,5 +1,5 @@
 #  -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
+# Copyright (C) 2007-2021  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
@@ -45,9 +45,7 @@ variables:
 
   - salome.sg              : salome object to communicate with the graphical user interface (if any)
       - methods:
-         - updateObjBrowser(bool):
-         - getActiveStudyId():
-         - getActiveStudyName():
+         - updateObjBrowser():
 
          - SelectedCount():      returns number of selected objects
          - getSelected(i):       returns entry of selected object number i
@@ -65,7 +63,6 @@ variables:
          - IDToObject(Entry):    returns CORBA reference from entry
 
   - salome.myStudyName     : active Study Name
-  - salome.myStudyId       : active Study Id
   - salome.myStudy         : the active Study itself (CORBA ior)
       - methods : defined in SALOMEDS.idl
 
@@ -78,7 +75,6 @@ variables:
 #  \param salome.lcc             : instance of lifeCycleCORBA class (SALOME_LifeCycleCORBA)
 #  \param salome.sg              : Salome object to communicate with the graphical user interface, if running (see interface in salome_iapp::SalomeOutsideGUI)
 #  \param salome.myStudyName     : active Study Name
-#  \param salome.myStudyId       : active Study Id
 #  \param salome.myStudy         : the active Study (interface SALOMEDS::Study)
 
 #
@@ -110,13 +106,13 @@ MATCH_ENDING_PATTERN="site-packages" + os.path.sep + "salome"
 
 def extend_path(pname):
     for dir in sys.path:
-        if not isinstance(dir, basestring) or not os.path.isdir(dir) or not dir.endswith(MATCH_ENDING_PATTERN):
+        if not isinstance(dir, str) or not os.path.isdir(dir) or not dir.endswith(MATCH_ENDING_PATTERN):
             continue
         subdir = os.path.join(dir, pname)
         # XXX This may still add duplicate entries to path on
         # case-insensitive filesystems
         if os.path.isdir(subdir) and subdir not in __path__:
-            if verbose(): print "INFO - The directory %s is appended to sys.path" % subdir
+            if verbose(): print("INFO - The directory %s is appended to sys.path" % subdir)
             __path__.append(subdir)
 
 extend_path(ROOT_PYTHONPACKAGE_NAME)
@@ -165,93 +161,172 @@ if not flags:
 #    sys.setdlopenflags(flags)
 #    pass
 
-orb, lcc, naming_service, cm,sg=None,None,None,None,None
-myStudyManager, myStudyId, myStudy, myStudyName=None,None,None,None
+orb, lcc, naming_service, cm, sg, esm, dsm, modulcat = None,None,None,None,None,None,None,None
+myStudy, myStudyName = None,None
 
-def setCurrentStudy(theStudy):
-    """
-    Change current study : an existing one given by a study object.
+salome_initial=True
 
-    :param theStudy: the study CORBA object to set as current study
-    """
-    global myStudyId, myStudy, myStudyName
-    myStudyId, myStudy, myStudyName =salome_study.setCurrentStudy(theStudy)
+__EMB_SERVANT_ENV_VAR_NAME = "SALOME_EMB_SERVANT"
 
-def setCurrentStudyId(theStudyId=0):
-    """
-    Change current study : an existing or new one given by Id.
+def standalone():
+    import os
+    os.environ[__EMB_SERVANT_ENV_VAR_NAME] = "1"
 
-    :param theStudyId: the study Id (optional argument)
-           0      : create a new study (default).
-           n (>0) : try connection to study with Id = n, or create a new one
-                      if study not found.
-    """
-    global myStudyId, myStudy, myStudyName
-    myStudyId, myStudy, myStudyName =salome_study.setCurrentStudyId(theStudyId)
+def salome_init(path=None, embedded=False):
+    import os
+    if __EMB_SERVANT_ENV_VAR_NAME in os.environ:
+        salome_init_without_session()
+    else:
+        import KernelBasis
+        if KernelBasis.getSSLMode():
+            salome_init_without_session()
+        else:
+            salome_init_with_session(path, embedded)
+
+class StandAloneLifecyle:
+    def __init__(self, containerManager, resourcesManager):
+        self._cm = containerManager
+        self._rm = resourcesManager
+
+    def FindOrLoadComponent(self,contName,moduleName):
+        global orb
+        import importlib
+        builder_name = moduleName + "_SalomeSessionless"
+        moduleObj = importlib.import_module(builder_name)
+        result, orb = moduleObj.buildInstance(orb)
+        return result
+        #raise RuntimeError("Undealed situation cont = {} module = {}".format(contName,moduleName))
+
+    def getContainerManager(self):
+      return self._cm
+
+    def getResourcesManager(self):
+      return self._rm
+
+def salome_init_without_session():
+    global lcc,myStudy,orb,modulcat,sg,cm
+    import KernelBasis
+    KernelBasis.setSSLMode(True)
+    import KernelDS
+    myStudy = KernelDS.myStudy()
+    import CORBA
+    orb=CORBA.ORB_init([''])
+    import KernelModuleCatalog
+    import SALOME_ModuleCatalog
+    from salome_kernel import list_of_catalogs_regarding_environement
+    modulcat = KernelModuleCatalog.myModuleCatalog( list_of_catalogs_regarding_environement() )
+    import KernelLauncher
+    cm = KernelLauncher.myContainerManager()
+    lcc = StandAloneLifecyle(cm, KernelLauncher.myResourcesManager())
+    # activate poaManager to accept co-localized CORBA calls.
+    poa = orb.resolve_initial_references("RootPOA")
+    poaManager = poa._get_the_POAManager()
+    poaManager.activate()
+    sg = SalomeOutsideGUI()
+    salome_study_init_without_session()
 
-salome_initial=1
-def salome_init(theStudyId=0,embedded=0):
+def salome_init_with_session(path=None, embedded=False):
     """
-    Performs only once SALOME general purpose intialisation for scripts.
-    optional argument : theStudyId
-      When in embedded interpreter inside IAPP, theStudyId is not used
-      When used without GUI (external interpreter)
-        0      : create a new study (default).
-        n (>0) : try connection to study with Id = n, or create a new one
-                 if study not found.
-                 If study creation, its Id may be different from theStudyId !
+    Performs only once SALOME general purpose initialisation for scripts.
     Provides:
     orb             reference to CORBA
     lcc             a LifeCycleCorba instance
     naming_service  a naming service instance
     cm              reference to the container manager
+    esm             reference to external server manager
+    dsm             reference to shared dataserver manager
+    modulcat        reference to modulecatalog instance
     sg              access to SALOME GUI (when linked with IAPP GUI)
-    myStudyManager  the study manager
-    myStudyId       active study identifier
     myStudy         active study itself (CORBA reference)
     myStudyName     active study name
     """
     global salome_initial
-    global orb, lcc, naming_service, cm
+    global orb, lcc, naming_service, cm, esm, dsm, modulcat
     global sg
-    global myStudyManager, myStudyId, myStudy, myStudyName
-
+    global myStudy, myStudyName
+    import KernelBasis
+    KernelBasis.setSSLMode(False)
     try:
         if salome_initial:
-            salome_initial=0
+            salome_initial=False
             sg = salome_iapp_init(embedded)
-            orb, lcc, naming_service, cm = salome_kernel_init()
-            myStudyManager, myStudyId, myStudy, myStudyName = salome_study_init(theStudyId)
+            orb, lcc, naming_service, cm, esm, dsm, modulcat = salome_kernel_init()
+            myStudy, myStudyName = salome_study_init(path)
             pass
         pass
-    except RuntimeError, inst:
+    except RuntimeError as inst:
         # wait a little to avoid trace mix
         import time
         time.sleep(0.2)
         x = inst
-        print "salome.salome_init():", x
-        print """
+        print("salome.salome_init():", x)
+        print("""
         ============================================
         May be there is no running SALOME session
         salome.salome_init() is intended to be used
         within an already running session
         ============================================
-        """
+        """)
         raise
     
 def salome_close():
-    global salome_initial, myStudy, myStudyId, myStudyName
+    global salome_initial, myStudy, myStudyName
     try:
-        # study can be closed either from GUI or directly with salome.myStudy.Close()
-        myStudy.Close()
+        # study can be clear either from GUI or directly with salome.myStudy.Clear()
+        myStudy.Clear()
     except:
         pass
-    salome_initial=1
+    salome_initial=True
     salome_iapp_close()
     salome_study_close()
-    myStudyId, myStudy, myStudyName=None,None,None
+    myStudy, myStudyName = None, None
+    import KernelDS
+    KernelDS.KillGlobalSessionInstance()
+    pass
+
+def salome_NS():
+    import CORBA
+    import CosNaming
+    orb = CORBA.ORB_init()
+    ns0 = orb.resolve_initial_references("NameService")
+    return ns0._narrow(CosNaming.NamingContext)
+
+def salome_walk_on_containers(ns,root):
+    import CosNaming
+    it = ns.list(0)[1]
+    if not it:
+        return
+    cont = True
+    while cont:
+        cont,obj = it.next_one()
+        if cont:
+            if obj.binding_name[0].kind == "object":
+                import Engines
+                corbaObj = ns.resolve(obj.binding_name)
+                if isinstance(corbaObj,Engines._objref_Container):
+                    yield corbaObj,(root,obj.binding_name[0].id)
+            else:
+                father = ns.resolve([obj.binding_name[0]])
+                for elt,elt2 in salome_walk_on_containers(father,root+[obj.binding_name[0].id]):
+                    yield elt,elt2
+            pass
+        pass
     pass
 
+def salome_shutdown_containers():
+    salome_init()
+    ns=salome_NS()
+    li = [elt for elt in salome_walk_on_containers(ns,[""])]
+    print("Number of containers in NS : {}".format(len(li)))
+    for cont,(root,cont_name) in li:
+        try:
+            cont.Shutdown()
+        except:
+            pass
+        ref_in_ns = "/".join(root+[cont_name])
+        naming_service.Destroy_Name(ref_in_ns)
+    print("Number of containers in NS after clean : {}".format( len( list(salome_walk_on_containers(ns,[""])) )))
+
 
 #to expose all objects to pydoc
 __all__=dir()