Salome HOME
PR: mergefrom_PRAS_br3_06Nov04
authorprascle <prascle>
Fri, 5 Nov 2004 15:54:41 +0000 (15:54 +0000)
committerprascle <prascle>
Fri, 5 Nov 2004 15:54:41 +0000 (15:54 +0000)
32 files changed:
bin/runSalome.py
src/Container/SALOME_Container.cxx
src/DataTypeCatalog/SALOME_DataTypeCatalog_Handler.cxx
src/DataTypeCatalog/SALOME_DataTypeCatalog_Server.cxx
src/Loader/InquireServersQThread.cxx
src/Loader/SALOME_Session_Loader.cxx
src/MPIContainer/SALOME_MPIContainer.cxx
src/Makefile.in
src/ModuleCatalog/SALOME_ModuleCatalog_Server.cxx
src/NamingService/Makefile.in
src/NamingService/NamingService_WaitForServerReadiness.cxx [new file with mode: 0644]
src/NamingService/NamingService_WaitForServerReadiness.hxx [new file with mode: 0644]
src/Registry/SALOME_Registry_Server.cxx
src/RessourcesCatalog/SALOME_RessourcesCatalog_Handler.cxx
src/RessourcesCatalog/SALOME_RessourcesCatalog_Server.cxx
src/SALOMEGUI/PyInterp_base.cxx
src/SALOMEGUI/QAD_PyInterp_mono.cxx
src/SALOMELocalTrace/LocalTraceBufferPool.cxx [new file with mode: 0644]
src/SALOMELocalTrace/LocalTraceBufferPool.hxx [new file with mode: 0644]
src/SALOMELocalTrace/LocalTraceCollector.cxx [new file with mode: 0644]
src/SALOMELocalTrace/LocalTraceCollector.hxx [new file with mode: 0644]
src/SALOMELocalTrace/LocalTrace_WaitForServerReadiness.cxx [new file with mode: 0644]
src/SALOMELocalTrace/LocalTrace_WaitForServerReadiness.hxx [new file with mode: 0644]
src/SALOMELocalTrace/Makefile.in
src/SALOMELocalTrace/utilities.h [new file with mode: 0644]
src/SALOMELogger/Makefile.in [deleted file]
src/SALOMELogger/SALOME_LoggerClient.cxx [deleted file]
src/Session/SALOME_Session_Server.cxx
src/Session/Session_ServerThread.cxx
src/Session/Session_ServerThread.hxx
src/Utils/Makefile.in
src/Utils/duplicate.cxx

index 400866a1bef3363ae4388902c6b383776ac53a99..1274e9a4530a388ba25c31ec90f2396f77698fb5 100755 (executable)
@@ -1,36 +1,14 @@
 #!/usr/bin/env python
 
 import sys, os, string, glob, time, pickle
+import orbmodule
 
-### read launch configure xml file and command line options
-import launchConfigureParser
-args = launchConfigureParser.args
-
-### kill servers if it is need
-
-from killSalome import killAllPorts
+process_id = {}
 
-def killLocalPort():
-    from killSalomeWithPort import killMyPort
-    my_port=str(args['port'])
-    try:
-        killMyPort(my_port)
-    except:
-        print "problem in killLocalPort()"
-        pass
-    pass
-    
-if args['killall']:
-    killAllPorts()
-elif args['portkill']:
-    killLocalPort()
-       
 # -----------------------------------------------------------------------------
-#
-# Fonctions helper pour ajouter des variables d'environnement
-#
 
 def add_path(directory, variable_name):
+    """Function helper to add environment variables"""
     if not os.environ.has_key(variable_name):
         os.environ[variable_name] = ""
         pass
@@ -51,359 +29,540 @@ def add_path(directory, variable_name):
         if variable_name == "PYTHONPATH":
             sys.path[:0] = [directory]
 
+# -----------------------------------------------------------------------------
+
+def get_config():
+    """
+    Get list of modules, paths.
+    
+    Read args from launch configure xml file and command line options.
+    Check variables <module>_ROOT_DIR and set list of used modules.
+    Return args, modules_list, modules_root_dir    
+    """
+    
+    # read args from launch configure xml file and command line options
+    
+    import launchConfigureParser
+    args = launchConfigureParser.args
+    
+    # Check variables <module>_ROOT_DIR
+    # and set list of used modules (without KERNEL)
+
+    modules_list = []
+    if args.has_key("modules"):
+        modules_list += args["modules"]
+    # KERNEL must be last in the list to locate it at the first place in PATH 
+    modules_list[:0] = ["KERNEL"]
+    modules_list.reverse()
+
+    modules_root_dir = {}
+
+    to_remove_list=[]
+    for module in modules_list :
+        module_variable=module.upper()+"_ROOT_DIR"
+        if not os.environ.has_key(module_variable):
+            print "*******************************************************"
+            print "*"
+            print "* Environment variable",module_variable,"must be set"
+            print "* Module", module, "will be not available"
+            print "*"
+            print "********************************************************"
+            to_remove_list.append(module)
+            continue
+            pass
+        module_root_dir = os.environ[module_variable]
+        modules_root_dir[module]=module_root_dir
+
+    for to_remove in to_remove_list:
+        modules_list.remove(to_remove)
+
+    while "KERNEL" in modules_list:
+        modules_list.remove("KERNEL")
+        pass
+
+    if "SUPERV" in modules_list and not 'superv' in args['standalone']:
+        args['standalone'].append("superv")
+        pass
+   
+    return args, modules_list, modules_root_dir
 
-init_time = os.times()
 # -----------------------------------------------------------------------------
-#
-# Check variables <module>_ROOT_DIR and set list of used modules (without KERNEL)
-# Add to the PATH-variables modules' specific paths
-#
-modules_list = []
-if args.has_key("modules"):
-    modules_list += args["modules"]
-modules_list[:0] = ["KERNEL"] # KERNEL must be last in the list to locate it at the first place in PATH variables
-modules_list.reverse()
-
-modules_root_dir = {}
-modules_root_dir_list = []
-python_version="python%d.%d" % sys.version_info[0:2]
-
-to_remove_list=[]
-for module in modules_list :
-    module_variable=module.upper()+"_ROOT_DIR"
-    if not os.environ.has_key(module_variable):
-        print "*******************************************************************************"
-        print "*"
-        print "* Environment variable",module_variable,"must be set"
-        print "* Module", module, "will be not available"
-        print "*"
-        print "*******************************************************************************"
-        to_remove_list.append(module)
-        continue
+
+def set_env(args, modules_list, modules_root_dir):
+    """Add to the PATH-variables modules specific paths"""
+    
+    python_version="python%d.%d" % sys.version_info[0:2]
+    modules_root_dir_list = []
+    modules_list = modules_list[:] + ["KERNEL"] 
+    for module in modules_list :
+        module_root_dir = modules_root_dir[module]
+        modules_root_dir_list[:0] = [module_root_dir]
+        add_path(os.path.join(module_root_dir,"lib",args['appname']),
+                 "LD_LIBRARY_PATH")
+        add_path(os.path.join(module_root_dir,"bin",args['appname']),
+                 "PATH")
+        if os.path.exists(module_root_dir + "/examples") :
+            add_path(os.path.join(module_root_dir,"examples"),
+                     "PYTHONPATH")
+        add_path(os.path.join(module_root_dir,"bin",args['appname']),
+                 "PYTHONPATH")
+        add_path(os.path.join(module_root_dir,"lib",
+                              python_version,"site-packages",args['appname']),
+                 "PYTHONPATH")
+        add_path(os.path.join(module_root_dir,"lib",args['appname']),
+                 "PYTHONPATH")
+        add_path(os.path.join(module_root_dir,"lib",
+                              python_version,"site-packages",args['appname'],
+                              "shared_modules"),
+                 "PYTHONPATH")
+
+    os.environ["SALOMEPATH"]=":".join(modules_root_dir_list)
+    
+    # special path for logger lib if needeed
+    
+    os.environ["SALOME_trace"]="local"
+    if args['logger']:
+        os.environ["SALOME_trace"]="with_logger"
+        locdir=os.environ['PWD']
+        libtracedir=os.path.join(locdir,"libSalomeTrace")
+        libtrace = os.path.join(modules_root_dir["KERNEL"],"lib",
+                                args['appname'],
+                                "libSALOMELoggerClient.so.0.0.0")
+        libtraceln = os.path.join(libtracedir,"libSALOMELocalTrace.so")
+        aCommand = 'rm -rf ' + libtracedir + "; "
+        aCommand += 'mkdir ' + libtracedir + "; "
+        aCommand += 'ln -s ' + libtrace + " " + libtraceln + "; "
+        aCommand += 'ln -s ' + libtrace + " " + libtraceln + ".0; "
+        aCommand += 'ln -s ' + libtrace + " " + libtraceln + ".0.0.0; "
+        os.system(aCommand)
+        add_path(libtracedir, "LD_LIBRARY_PATH")
+
+    # set environment for SMESH plugins
+
+    if "SMESH" in modules_list:
+        os.environ["SMESH_MeshersList"]="StdMeshers"
+        if not os.environ.has_key("SALOME_StdMeshersResources"):
+            os.environ["SALOME_StdMeshersResources"] \
+            = modules_root_dir["SMESH"]+"/share/"+args["appname"]+"/resources"
+            pass
+        if args.has_key("SMESH_plugins"):
+            for plugin in args["SMESH_plugins"]:
+                if os.environ.has_key(plugin.upper()+"_ROOT_DIR"):
+                    os.environ["SMESH_MeshersList"] \
+                    = os.environ["SMESH_MeshersList"]+":"+plugin
+                    plugin_root = os.environ[plugin.upper()+"_ROOT_DIR"]
+                    if not os.environ.has_key("SALOME_"+plugin+"Resources"):
+                        os.environ["SALOME_"+plugin+"Resources"] \
+                        = plugin_root+"/share/"+args["appname"]+"/resources"
+                    add_path(os.path.join(plugin_root,"lib",python_version,
+                                          "site-packages",args['appname']),
+                             "PYTHONPATH")
+                    add_path(os.path.join(plugin_root,"lib",args['appname']),
+                             "PYTHONPATH")
+                    add_path(os.path.join(plugin_root,"lib",args['appname']),
+                             "LD_LIBRARY_PATH")
+                    add_path(os.path.join(plugin_root,"bin",args['appname']),
+                             "PYTHONPATH")
+                    add_path(os.path.join(plugin_root,"bin",args['appname']),
+                             "PATH")
+            pass
         pass
-    module_root_dir = os.environ[module_variable]
-    modules_root_dir[module]=module_root_dir
-    modules_root_dir_list[:0] = [module_root_dir]
-    add_path(os.path.join(module_root_dir,"lib",args['appname']), "LD_LIBRARY_PATH")
-    add_path(os.path.join(module_root_dir,"bin",args['appname']), "PATH")
-    if os.path.exists(module_root_dir + "/examples") :
-        add_path(os.path.join(module_root_dir,"examples"), "PYTHONPATH")
-
-for to_remove in to_remove_list:
-    modules_list.remove(to_remove)
-
-while "KERNEL" in modules_list:
-    modules_list.remove("KERNEL")
-    pass
 
-# KERNEL must be last in the list to locate it at the first place in PYTHONPATH variable
-list_modules = modules_list[:] + ["KERNEL"] 
-for module in list_modules:
-    module_root_dir = modules_root_dir[module]
-    add_path(os.path.join(module_root_dir,"bin",args['appname']), "PYTHONPATH")
-    add_path(os.path.join(module_root_dir,"lib",python_version,"site-packages",args['appname']), "PYTHONPATH")
-    add_path(os.path.join(module_root_dir,"lib",args['appname']), "PYTHONPATH")
-    add_path(os.path.join(module_root_dir,"lib",python_version,"site-packages",args['appname'],"shared_modules"), "PYTHONPATH")
-      
-#os.environ["SALOMEPATH"]=":".join(modules_root_dir.values())
-os.environ["SALOMEPATH"]=":".join(modules_root_dir_list)
-if "SUPERV" in modules_list and not 'superv' in args['standalone']:
-    args['standalone'].append("superv")
-    pass
+    # set environment for SUPERV module
+    os.environ["ENABLE_MACRO_NODE"]="1"
+   
 
+# -----------------------------------------------------------------------------
 
+from killSalome import killAllPorts
+
+def killLocalPort():
+    """
+    kill servers from a previous SALOME exection, if needed,
+    on the same CORBA port
+    """
+    
+    from killSalomeWithPort import killMyPort
+    my_port=str(args['port'])
+    try:
+        killMyPort(my_port)
+    except:
+        print "problem in killLocalPort()"
+        pass
+    pass
+    
+    
+def kill_salome(args):
+    """
+    Kill servers from previous SALOME executions, if needed;
+    depending on args 'killall' or 'portkill', kill all executions,
+    or only execution on the same CORBA port
+    """
+
+    if args['killall']:
+        killAllPorts()
+    elif args['portkill']:
+        killLocalPort()
+       
 # -----------------------------------------------------------------------------
 #
 # Définition des classes d'objets pour le lancement des Server CORBA
 #
 
 class Server:
-   CMD=[]
-   if args['xterm']:
-       ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-hold']
-   else:
-       ARGS=[] 
-
-   def run(self):
-       global process_id
-       myargs=self.ARGS
-       if args['xterm']:
-           # (Debian) Transfert variable LD_LIBRARY_PATH aux shells fils (xterm)
-           env_ld_library_path=['env', 'LD_LIBRARY_PATH='+ os.getenv("LD_LIBRARY_PATH")]
-           myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path
-       command = myargs + self.CMD
-       #print "command = ", command
-       pid = os.spawnvp(os.P_NOWAIT, command[0], command)
-       process_id[pid]=self.CMD
+    """Generic class for CORBA server launch"""
+
+    def initArgs(self):
+        self.CMD=[]
+        self.ARGS=[]   
+        if self.args['xterm']:
+            self.ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-hold']
+
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+
+
+    def run(self):
+        global process_id
+        myargs=self.ARGS
+        if self.args['xterm']:
+            # (Debian) send LD_LIBRARY_PATH to children shells (xterm)
+            env_ld_library_path=['env', 'LD_LIBRARY_PATH='
+                                 + os.getenv("LD_LIBRARY_PATH")]
+            myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path
+        command = myargs + self.CMD
+        # print "command = ", command
+        pid = os.spawnvp(os.P_NOWAIT, command[0], command)
+        process_id[pid]=self.CMD
+
+# ---
 
 class CatalogServer(Server):
-   SCMD1=['SALOME_ModuleCatalog_Server','-common']
-   SCMD2=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml'] 
-
-   def setpath(self,modules_list):
-      cata_path=[]
-      list_modules = modules_list[:]
-      list_modules.reverse()
-      for module in ["KERNEL"] + list_modules:
-          module_root_dir=modules_root_dir[module]
-          module_cata=module+"Catalog.xml"
-          print "   ", module_cata
-          cata_path.extend(glob.glob(os.path.join(module_root_dir,"share",args['appname'],"resources",module_cata)))
-      self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
+        self.SCMD2=['-personal',
+                    '${HOME}/Salome/resources/CatalogModulePersonnel.xml'] 
+
+    def setpath(self,modules_list):
+        cata_path=[]
+        list_modules = modules_list[:]
+        list_modules.reverse()
+        for module in ["KERNEL"] + list_modules:
+            module_root_dir=modules_root_dir[module]
+            module_cata=module+"Catalog.xml"
+            print "   ", module_cata
+            cata_path.extend(
+                glob.glob(os.path.join(module_root_dir,
+                                       "share",self.args['appname'],
+                                       "resources",module_cata)))
+        self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
+
+# ---
 
 class SalomeDSServer(Server):
-   CMD=['SALOMEDS_Server']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOMEDS_Server']
+
+# ---
 
 class RegistryServer(Server):
-   CMD=['SALOME_Registry_Server', '--salome_session','theSession']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
+
+# ---
 
 class ContainerCPPServer(Server):
-   #CMD=['SALOME_Container','FactoryServer','-ORBInitRef','NameService=corbaname::localhost']
-   CMD=['SALOME_Container','FactoryServer']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_Container','FactoryServer']
+
+# ---
 
 class ContainerPYServer(Server):
-   #CMD=['SALOME_ContainerPy.py','FactoryServerPy','-ORBInitRef','NameService=corbaname::localhost']
-   CMD=['SALOME_ContainerPy.py','FactoryServerPy']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_ContainerPy.py','FactoryServerPy']
+
+# ---
 
 class ContainerSUPERVServer(Server):
-   #CMD=['SALOME_Container','SuperVisionContainer','-ORBInitRef','NameService=corbaname::localhost']
-   CMD=['SALOME_Container','SuperVisionContainer']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_Container','SuperVisionContainer']
+
+# ---
 
 class LoggerServer(Server):
-   CMD=['SALOME_Logger_Server', 'logger.log']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_Logger_Server', 'logger.log']
+
+# ---
 
 class SessionLoader(Server):
-   CMD=['SALOME_Session_Loader']
-   if "cpp" in args['containers']:
-       CMD=CMD+['CPP']
-   if "python" in args['containers']:
-       CMD=CMD+['PY']
-   if "superv" in args['containers']:
-       CMD=CMD+['SUPERV']
-   if args['gui']:
-       CMD=CMD+['GUI']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_Session_Loader']
+        if "cppContainer" in self.args['standalone'] \
+        or "cppContainer" in self.args['embedded']:
+            self.CMD=self.CMD+['CPP']
+        if "pyContainer" in self.args['standalone'] \
+        or "pyContainer" in self.args['embedded']:
+            self.CMD=self.CMD+['PY']
+        if "supervContainer" in self.args['containers'] \
+        or "supervContainer" in self.args['standalone']:
+            self.CMD=self.CMD+['SUPERV']
+        if self.args['gui']:
+            self.CMD=self.CMD+['GUI']
+        print self.CMD
+
+# ---
 
 class SessionServer(Server):
-   SCMD1=['SALOME_Session_Server']
-   SCMD2=[]
-   if 'registry' in args['embedded']:
-       SCMD1+=['--with','Registry','(','--salome_session','theSession',')']
-   if 'moduleCatalog' in args['embedded']:
-       SCMD1+=['--with','ModuleCatalog','(','-common']
-       SCMD2+=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
-   if 'study' in args['embedded']:
-       SCMD2+=['--with','SALOMEDS','(',')']
-   if 'cppContainer' in args['embedded']:
-       SCMD2+=['--with','Container','(','FactoryServer',')']
-
-   def setpath(self,modules_list):
-      cata_path=[]
-      list_modules = modules_list[:]
-      list_modules.reverse()
-      for module in ["KERNEL"] + list_modules:
-          module_root_dir=modules_root_dir[module]
-          module_cata=module+"Catalog.xml"
-          print "   ", module_cata
-          cata_path.extend(glob.glob(os.path.join(module_root_dir,"share",args['appname'],"resources",module_cata)))
-      if 'moduleCatalog' in args['embedded']:
-          self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
-      else:
-          self.CMD=self.SCMD1 + self.SCMD2
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.SCMD1=['SALOME_Session_Server']
+        self.SCMD2=[]
+        if 'registry' in self.args['embedded']:
+            self.SCMD1+=['--with','Registry',
+                         '(','--salome_session','theSession',')']
+        if 'moduleCatalog' in self.args['embedded']:
+            self.SCMD1+=['--with','ModuleCatalog','(','-common']
+            self.SCMD2+=['-personal',
+                     '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
+        if 'study' in self.args['embedded']:
+            self.SCMD2+=['--with','SALOMEDS','(',')']
+        if 'cppContainer' in self.args['embedded']:
+            self.SCMD2+=['--with','Container','(','FactoryServer',')']
+
+    def setpath(self,modules_list,modules_root_dir):
+        cata_path=[]
+        list_modules = modules_list[:]
+        list_modules.reverse()
+        for module in ["KERNEL"] + list_modules:
+            module_root_dir=modules_root_dir[module]
+            module_cata=module+"Catalog.xml"
+            print "   ", module_cata
+            cata_path.extend(
+                glob.glob(os.path.join(module_root_dir,"share",
+                                       self.args['appname'],"resources",
+                                       module_cata)))
+        if 'moduleCatalog' in self.args['embedded']:
+            self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
+        else:
+            self.CMD=self.SCMD1 + self.SCMD2
+
+##      # arguments SALOME_Session_Server pour ddd
+##      comm_ddd=""
+##      for mot in self.CMD:
+##          if mot == "(":
+##              comm_ddd+='"(" '
+##          elif mot == ")":
+##              comm_ddd+='")" '
+##          else:
+##              comm_ddd+=mot+" "
+##      print comm_ddd
+      
+# ---
 
 class NotifyServer(Server):
-    myLogName = os.environ["LOGNAME"]
-    CMD=['notifd','-c',modules_root_dir["KERNEL"]+'/share/salome/resources/channel.cfg', '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior', '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior']
-
-# -----------------------------------------------------------------------------
-#
-# initialisation des variables d'environnement
-#
-
-os.environ["SALOME_trace"]="local"
-if args['logger']:
-   os.environ["SALOME_trace"]="with_logger"
-   locdir=os.environ['PWD']
-   libtracedir=os.path.join(locdir,"libSalomeTrace")
-   libtrace = os.path.join(modules_root_dir["KERNEL"],"lib",args['appname'],"libSALOMELoggerClient.so.0.0.0")
-   libtraceln = os.path.join(libtracedir,"libSALOMELocalTrace.so")
-   aCommand = 'rm -rf ' + libtracedir + "; "
-   aCommand += 'mkdir ' + libtracedir + "; "
-   aCommand += 'ln -s ' + libtrace + " " + libtraceln + "; "
-   aCommand += 'ln -s ' + libtrace + " " + libtraceln + ".0; "
-   aCommand += 'ln -s ' + libtrace + " " + libtraceln + ".0.0.0; "
-   os.system(aCommand)
-   add_path(libtracedir, "LD_LIBRARY_PATH")
-
-# set environment for SMESH plugins
-
-if "SMESH" in modules_list:
-    os.environ["SMESH_MeshersList"]="StdMeshers"
-    if not os.environ.has_key("SALOME_StdMeshersResources"):
-        os.environ["SALOME_StdMeshersResources"] = modules_root_dir["SMESH"]+"/share/"+args["appname"]+"/resources"
-        pass
-    if args.has_key("SMESH_plugins"):
-        for plugin in args["SMESH_plugins"]:
-            if os.environ.has_key(plugin.upper()+"_ROOT_DIR"):
-                os.environ["SMESH_MeshersList"]=os.environ["SMESH_MeshersList"]+":"+plugin
-                plugin_root = os.environ[plugin.upper()+"_ROOT_DIR"]
-                if not os.environ.has_key("SALOME_"+plugin+"Resources"):
-                    os.environ["SALOME_"+plugin+"Resources"] = plugin_root+"/share/"+args["appname"]+"/resources"
-                add_path(os.path.join(plugin_root,"lib",python_version,"site-packages",args['appname']), "PYTHONPATH")
-                add_path(os.path.join(plugin_root,"lib",args['appname']), "PYTHONPATH")
-                add_path(os.path.join(plugin_root,"lib",args['appname']), "LD_LIBRARY_PATH")
-                add_path(os.path.join(plugin_root,"bin",args['appname']), "PYTHONPATH")
-                add_path(os.path.join(plugin_root,"bin",args['appname']), "PATH")
-        pass
-    pass
-
-# set environment for SUPERV module
-os.environ["ENABLE_MACRO_NODE"]="1"
-
-import orbmodule
+    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/channel.cfg',
+                  '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
+                  '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior']
 
 #
 # -----------------------------------------------------------------------------
-#
 
 def startGUI():
-  import SALOME
-  session=clt.waitNS("/Kernel/Session",SALOME.Session)
-
-  #
-  # Activation du GUI de Session Server
-  #
-       
-  session.GetInterface()
+    """Salome Session Graphic User Interface activation"""
+    import SALOME
+    session=clt.waitNS("/Kernel/Session",SALOME.Session)
+    session.GetInterface()
   
-#
 # -----------------------------------------------------------------------------
-#
 
-def startSalome():
+def startSalome(args, modules_list, modules_root_dir):
+    """Launch all SALOME servers requested by args"""
+    init_time = os.times()
 
-  #
-  # Lancement Session Loader
-  #
+    #
+    # Lancement Session Loader
+    #
 
-  if args['gui']:
-     SessionLoader().run()
+    print "startSalome ", args
+    
+    if args['gui']:
+        myServer=SessionLoader(args)
+        myServer.run()
 
-  #
-  # Initialisation ORB et Naming Service
-  #
+    #
+    # Initialisation ORB et Naming Service
+    #
    
-  clt=orbmodule.client()
-
-  # (non obligatoire) Lancement Logger Server et attente de sa disponibilite dans le naming service
-  #
-
-  if args['logger']:
-       LoggerServer().run()
-       clt.waitLogger("Logger")
-
-  # Notify Server launch
-  #
-  NotifyServer().run()
-
-  #
-  # Lancement Registry Server, attente de la disponibilité du Registry dans le Naming Service
-  #
-  if 'registry' not in args['embedded']:
-      RegistryServer().run()
-      clt.waitNS("/Registry")
-
-  #
-  # Lancement Catalog Server, attente de la disponibilité du Catalog Server dans le Naming Service
-  #
-
-  if 'moduleCatalog' not in args['embedded']:
-      cataServer=CatalogServer()
-      cataServer.setpath(modules_list)
-      cataServer.run()
-      import SALOME_ModuleCatalog
-      clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
-
-  #
-  # Lancement SalomeDS Server, attente de la disponibilité du SalomeDS dans le Naming Service
-  #
-
-  os.environ["CSF_PluginDefaults"]=os.path.join(modules_root_dir["KERNEL"],"share",args['appname'],"resources")
-  os.environ["CSF_SALOMEDS_ResourcesDefaults"]=os.path.join(modules_root_dir["KERNEL"],"share",args['appname'],"resources")
-
-  if "GEOM" in modules_list:
-       print "GEOM OCAF Resources"
-       os.environ["CSF_GEOMDS_ResourcesDefaults"]=os.path.join(modules_root_dir["GEOM"],"share",args['appname'],"resources")
+    clt=orbmodule.client()
+
+    # (non obligatoire) Lancement Logger Server
+    # et attente de sa disponibilite dans le naming service
+    #
+
+    if args['logger']:
+        myServer=LoggerServer(args)
+        myServer.run()
+        clt.waitLogger("Logger")
+
+    # Notify Server launch
+    #
+
+    myServer=NotifyServer(args,modules_root_dir)
+    myServer.run()
+
+    #
+    # Lancement Registry Server,
+    # attente de la disponibilité du Registry dans le Naming Service
+    #
+
+    if 'registry' not in args['embedded']:
+        myServer=RegistryServer(args)
+        myServer.run()
+        clt.waitNS("/Registry")
+
+    #
+    # Lancement Catalog Server,
+    # attente de la disponibilité du Catalog Server dans le Naming Service
+    #
+
+    if 'moduleCatalog' not in args['embedded']:
+        cataServer=CatalogServer(args)
+        cataServer.setpath(modules_list)
+        cataServer.run()
+        import SALOME_ModuleCatalog
+        clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
+
+    #
+    # Lancement SalomeDS Server,
+    # attente de la disponibilité du SalomeDS dans le Naming Service
+    #
+
+    os.environ["CSF_PluginDefaults"] \
+    = os.path.join(modules_root_dir["KERNEL"],"share",
+                   args['appname'],"resources")
+    os.environ["CSF_SALOMEDS_ResourcesDefaults"] \
+    = os.path.join(modules_root_dir["KERNEL"],"share",
+                   args['appname'],"resources")
+
+    if "GEOM" in modules_list:
+        print "GEOM OCAF Resources"
+        os.environ["CSF_GEOMDS_ResourcesDefaults"] \
+        = os.path.join(modules_root_dir["GEOM"],"share",
+                       args['appname'],"resources")
        print "GEOM Shape Healing Resources"
-        os.environ["CSF_ShHealingDefaults"]=os.path.join(modules_root_dir["GEOM"],"share",args['appname'],"resources")
+        os.environ["CSF_ShHealingDefaults"] \
+        = os.path.join(modules_root_dir["GEOM"],"share",
+                       args['appname'],"resources")
 
-  if 'study' not in args['embedded']:
-      SalomeDSServer().run()
-      clt.waitNS("/myStudyManager")
+    if 'study' not in args['embedded']:
+        myServer=SalomeDSServer(args)
+        myServer.run()
+        clt.waitNS("/myStudyManager")
 
-  #
-  # Lancement Session Server
-  #
+    #
+    # Lancement Session Server
+    #
 
-  mySessionServ=SessionServer()
-  mySessionServ.setpath(modules_list)
-  mySessionServ.run()
+    mySessionServ = SessionServer(args)
+    mySessionServ.setpath(modules_list,modules_root_dir)
+    mySessionServ.run()
 
-  #
-  # Attente de la disponibilité du Session Server dans le Naming Service
-  #
+    #macomm2=['ddd']
+    #pid = os.spawnvp(os.P_NOWAIT, macomm2[0], macomm2)
+    #
+    # Attente de la disponibilité du Session Server dans le Naming Service
+    #
 
-  #import SALOME
-  #session=clt.waitNS("/Kernel/Session",SALOME.Session)
+    import SALOME
+    session=clt.waitNS("/Kernel/Session",SALOME.Session)
 
-  if os.getenv("HOSTNAME") == None:
-     if os.getenv("HOST") == None:
-        os.environ["HOSTNAME"]="localhost"
-     else:
-        os.environ["HOSTNAME"]=os.getenv("HOST")
+    if os.getenv("HOSTNAME") == None:
+        if os.getenv("HOST") == None:
+            os.environ["HOSTNAME"]="localhost"
+        else:
+            os.environ["HOSTNAME"]=os.getenv("HOST")
 
-  theComputer = os.getenv("HOSTNAME")
-  computerSplitName = theComputer.split('.')
-  theComputer = computerSplitName[0]
+    theComputer = os.getenv("HOSTNAME")
+    computerSplitName = theComputer.split('.')
+    theComputer = computerSplitName[0]
   
-  #
-  # Lancement Container C++ local, attente de la disponibilité du Container C++ local dans le Naming Service
-  #
+    #
+    # Lancement Container C++ local,
+    # attente de la disponibilité du Container C++ local dans le Naming Service
+    #
 
-  if 'cppContainer' in args['standalone']:
-         ContainerCPPServer().run()
-         clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
+    if 'cppContainer' in args['standalone']:
+        myServer=ContainerCPPServer(args)
+        myServer.run()
+        clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
 
-  #
-  # Lancement Container Python local, attente de la disponibilité du Container Python local dans le Naming Service
-  #
+    #
+    # Lancement Container Python local,
+    # attente de la disponibilité du Container Python local
+    # dans le Naming Service
+    #
 
-  if 'pyContainer' in args['standalone']:
-         ContainerPYServer().run()
-         clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
+    if 'pyContainer' in args['standalone']:
+        myServer=ContainerPYServer(args)
+        myServer.run()
+        clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
 
-  #
-  # Lancement Container Supervision local, attente de la disponibilité du Container Supervision local dans le Naming Service
-  #
+    #
+    # Lancement Container Supervision local,
+    # attente de la disponibilité du Container Supervision local
+    # dans le Naming Service
+    #
 
-  if 'supervContainer' in args['standalone']:
-      ContainerSUPERVServer().run()
-      clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
+    if 'supervContainer' in args['standalone']:
+        myServer=ContainerSUPERVServer(args)
+        myServer.run()
+        clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
 
-  end_time = os.times()
-  print
-  print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4] - init_time[4])
+    end_time = os.times()
+    print
+    print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
+                                                         - init_time[4])
 
-  return clt
+    return clt
 
-#
 # -----------------------------------------------------------------------------
-#
 
-process_id = {}
-if __name__ == "__main__":
+def useSalome(args, modules_list, modules_root_dir):
+    """
+    Launch all SALOME servers requested by args,
+    save list of process, give info to user,
+    show registered objects in Naming Service.
+    """
+    
     clt=None
     try:
-        clt = startSalome()
+        clt = startSalome(args, modules_list, modules_root_dir)
     except:
         print
         print
@@ -411,10 +570,9 @@ if __name__ == "__main__":
         
     #print process_id
     
-    filedict='/tmp/'+os.getenv('USER')+"_"+str(args['port'])+'_'+args['appname'].upper()+'_pidict'
-    #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
-    
-    
+    filedict = '/tmp/' + os.getenv('USER') + "_" + str(args['port']) \
+             + '_' + args['appname'].upper() + '_pidict'
+   
     process_ids = []
     try:
         fpid=open(filedict, 'r')
@@ -436,7 +594,8 @@ if __name__ == "__main__":
       killLocalPort()  --> kill this session
       killAllPorts()   --> kill all sessions
     
-    runSalome, with --killall option, starts with killing the processes resulting from the previous execution.
+    runSalome, with --killall option, starts with killing
+    the processes resulting from the previous execution.
     """%filedict
     
     #
@@ -447,3 +606,46 @@ if __name__ == "__main__":
         print
         print " --- registered objects tree in Naming Service ---"
         clt.showNS()
+
+    return clt
+
+# -----------------------------------------------------------------------------
+
+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.
+    """
+    fileEnv = '/tmp/' + os.getenv('USER') + "_" + str(args['port']) \
+            + '_' + args['appname'].upper() + '_env'
+    fenv=open(fileEnv,'w')
+    pickle.dump((args, modules_list, modules_root_dir),fenv)
+    fenv.close()
+    os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
+
+# -----------------------------------------------------------------------------
+
+def no_main():
+    """Salome Launch, when embedded in other application"""
+    fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
+    fenv=open(fileEnv,'r')
+    args, modules_list, modules_root_dir = pickle.load(fenv)
+    fenv.close()
+    kill_salome(args)
+    clt = useSalome(args, modules_list, modules_root_dir)
+    return clt
+
+# -----------------------------------------------------------------------------
+
+def main():
+    """Salome launch as a main application"""
+    args, modules_list, modules_root_dir = get_config()
+    kill_salome(args)
+    set_env(args, modules_list, modules_root_dir)
+    clt = useSalome(args, modules_list, modules_root_dir)
+    return clt,args
+
+# -----------------------------------------------------------------------------
+
+if __name__ == "__main__":
+   clt,args = main()
index a324089b700e75ecd93495514c2eebbd8dcce6e5..41a526d0a5ff8cc54122b90094e9057e798bae42 100644 (file)
@@ -35,6 +35,7 @@
 #include "SALOME_NamingService.hxx"
 #include "SALOME_Container_i.hxx"
 #include "utilities.h"
+#include "LocalTraceCollector.hxx"
 
 #ifdef CHECKTIME
 #include <Utils_Timer.hxx>
@@ -54,6 +55,13 @@ static PyMethodDef MethodPyVoidMethod[] = {{ NULL, NULL }};
 
 int main(int argc, char* argv[])
 {
+#ifdef HAVE_MPI2
+  MPI_Init(&argc,&argv);
+#endif
+  // Initialise the ORB.
+  ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance() ;
+  CORBA::ORB_var &orb = init( argc , argv ) ;
+  LocalTraceCollector *myThreadTrace = LocalTraceCollector::instance(orb);
   INFOS_COMPILATION;
   BEGIN_OF(argv[0]);
     
@@ -62,14 +70,6 @@ int main(int argc, char* argv[])
   Py_InitModule( "InitPyRunMethod" , MethodPyVoidMethod ) ;
   
   try{
-#ifdef HAVE_MPI2
-      MPI_Init(&argc,&argv);
-#endif
-    // Initialise the ORB.
-    ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance() ;
-    ASSERT(SINGLETON_<ORB_INIT>::IsAlreadyExisting()) ;
-    CORBA::ORB_var &orb = init( argc , argv ) ;
-    
     // Obtain a reference to the root POA.
     // obtain the root poa manager
     //
@@ -210,5 +210,7 @@ int main(int argc, char* argv[])
   MPI_Finalize();
 #endif
   END_OF(argv[0]);
+  delete myThreadTrace;
+  return 0 ;
 }
 
index 47f8fb92dee049c515b2b9b0b68baf561bf84023..26178c295926dbd5ba545269aa8569dd81291c43 100644 (file)
 
 #include "utilities.h"
 
+#include "SALOME_DataTypeCatalog_Handler.hxx"
+
+#include "utilities.h"
+
 using namespace std;
 
 // contains all the data types defined in the catalog
index a29401c51644720df8528bf20b2c7be0343efd8e..988cd896161285eec27e70914d055af93a47b6cf 100644 (file)
 #include "SALOME_NamingService.hxx"
 #include "SALOME_DataTypeCatalog_impl.hxx"
 #include "utilities.h"
+#include "LocalTraceCollector.hxx"
 #include "Utils_SINGLETON.hxx"
 using namespace std;
 
 int main(int argc,char **argv)
 {
+  // initialize the ORB
+  CORBA::ORB_ptr orb = CORBA::ORB_init (argc, argv);
+  LocalTraceCollector *myThreadTrace = LocalTraceCollector::instance(orb);
   try 
     {
       CosNaming::NamingContext_var _rootContext, catalogContext;
-      // initialize the ORB
-      CORBA::ORB_ptr orb = CORBA::ORB_init (argc, argv);
       // initialize POA
       //
       long TIMESleep = 250000000;
@@ -153,5 +155,6 @@ int main(int argc,char **argv)
     INFOS("Caught CORBA::Exception.")
       }
 
+  delete myThreadTrace;
   return 0;
 }
index c5cf7037771cb1d36949cf293df2d0a54189d9df..d93260dc2ae6690d4cac24408a45b0072a1924d5 100644 (file)
@@ -8,6 +8,7 @@
 //  $Header$
 
 using namespace std;
+#include "utilities.h"
 #include "InquireServersQThread.h"
 
 #include <qlabel.h>
@@ -34,7 +35,7 @@ using namespace std;
 #include "Utils_ORB_INIT.hxx"
 #include "Utils_SINGLETON.hxx"
 #include "SALOME_NamingService.hxx"
-#include "utilities.h"
+//#include "utilities.h"
 #include "OpUtil.hxx"
 
 #include CORBA_CLIENT_HEADER(SALOME_Session)
@@ -230,7 +231,7 @@ InquireServersQThread::InquireServersQThread( InquireServersGUI* r )
       myMessages[5] = str + "SALOME_Container FactoryServer" + "...";
       myServersCount++;
     }
-    if (strcmp(_argv[i],"PYTHON")==0) {
+    if (strcmp(_argv[i],"PY")==0) {
       myMessages[6] = str + "SALOME_ContainerPy.py FactoryServerPy" + "...";
       myServersCount++;
     }
index 3aff0456418d235168f796e540ade4ba60ea10ce..09cdad05e24a7b658ee469f2a1b2b44fa7b6989a 100644 (file)
@@ -19,6 +19,7 @@ using namespace std;
 #include "Utils_SINGLETON.hxx"
 #include "SALOME_NamingService.hxx"
 #include "utilities.h"
+#include "LocalTraceCollector.hxx"
 
 //! CORBA client for SALOME Session server : launch GUI
 /*!
@@ -30,6 +31,8 @@ using namespace std;
 
 int main(int argc, char **argv)
 {
+  CORBA::ORB_ptr orb = CORBA::ORB_init(argc,argv) ;
+  LocalTraceCollector *myThreadTrace = LocalTraceCollector::instance(orb);
 //VRV: T2.4 - Trace management improvement
   QApplication myQApp(argc, argv) ;
   InquireServersGUI myIS;
@@ -43,9 +46,7 @@ int main(int argc, char **argv)
 //VRV: T2.4 - Trace management improvement
   if (myIS.withGUI()) {
     try
-      {
-       CORBA::ORB_ptr orb = CORBA::ORB_init(argc,argv) ;
-       
+      {        
        SALOME_NamingService &NS = *SINGLETON_<SALOME_NamingService>::Instance() ;
        ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting()) ;
        NS.init_orb( orb ) ;
@@ -85,8 +86,10 @@ int main(int argc, char **argv)
       {
        INFOS("Caught unknown exception.");
       }
-    return 0 ;
   }
+  INFOS("Normal Exit"); // without this trace, Splash remains on screen !
+  delete myThreadTrace;
+  return 0 ;
 }
 
 
index f11dbb26de5c146920ba84a0d79eeca8d6a5f9dc..d6e19149ea3af1bd32633dae638bb67fc99bf4f0 100644 (file)
@@ -28,10 +28,12 @@ using namespace std;
 #include <iostream>
 #include "MPIContainer_i.hxx"
 #include "utilities.h"
+#include "LocalTraceCollector.hxx"
 #include <mpi.h>
 
 int main(int argc, char* argv[])
 {
+  LocalTraceCollector *myThreadTrace = LocalTraceCollector::instance();
   int nbproc, numproc;
   MPIContainer_i * myContainer;
 
@@ -116,5 +118,7 @@ int main(int argc, char* argv[])
     INFOS("Caught unknown exception.")
    }
   END_OF(argv[0]);
+  delete myThreadTrace;
+  return 0;
 }
 
index 1eaa66af2d8f26243cd0528f26d1b6f2eab143e8..684d6230548e7a8abb78b1ade1e252bcf0e4c887 100644 (file)
@@ -32,7 +32,7 @@ VPATH=.:@srcdir@
 
 @COMMENCE@
 
-SUBDIRS = MSG2QM SALOMELocalTrace Logger Utils SALOMELogger CASCatch PatchQt \
+SUBDIRS = MSG2QM SALOMELocalTrace Logger Utils CASCatch PatchQt \
           GenericObj MEDWrapper NamingService Registry \
          ModuleCatalog DataTypeCatalog RessourcesCatalog \
           Notification  NOTIFICATION_SWIG \
index a15d547596083c9e65ec16a904cfe451aad5a668..942c8f33d108fc7bb7ed2c25c0d94667c387a6d0 100644 (file)
@@ -29,6 +29,7 @@
 #include "SALOME_NamingService.hxx"
 #include "SALOME_ModuleCatalog_impl.hxx"
 #include "utilities.h"
+#include "LocalTraceCollector.hxx"
 #include "Utils_SINGLETON.hxx"
 
 #ifdef CHECKTIME
@@ -38,14 +39,13 @@ using namespace std;
 
 int main(int argc,char **argv)
 {
+  // initialize the ORB
+  CORBA::ORB_ptr orb = CORBA::ORB_init (argc, argv);
+  LocalTraceCollector *myThreadTrace = LocalTraceCollector::instance(orb);
   try 
     {
       CosNaming::NamingContext_var _rootContext, catalogContext;
 
-      // initialize the ORB
-
-      CORBA::ORB_ptr orb = CORBA::ORB_init (argc, argv);
-
       // initialize POA
       //
       long TIMESleep = 250000000;
@@ -166,5 +166,6 @@ int main(int argc,char **argv)
     INFOS("Caught CORBA::Exception.")
       }
 
+  delete myThreadTrace;
   return 0;
 }
index 395e929221a1a0f75730df5feb7b6f2c4657dd44..2951501b1a9ec9f1c8d6b5334cb6eb5a04eebc44 100644 (file)
@@ -38,11 +38,16 @@ EXPORT_PYSCRIPTS = SALOME_NamingServicePy.py
 
 EXPORT_HEADERS = \
        SALOME_NamingService.hxx \
-       ServiceUnreachable.hxx
+       ServiceUnreachable.hxx \
+       NamingService_WaitForServerReadiness.hxx
+
 # Libraries targets
 
 LIB = libSalomeNS.la 
-LIB_SRC = SALOME_NamingService.cxx ServiceUnreachable.cxx
+LIB_SRC = \
+       SALOME_NamingService.cxx \
+       ServiceUnreachable.cxx \
+       NamingService_WaitForServerReadiness.cxx
 
 LDFLAGS+= -lOpUtil
 
diff --git a/src/NamingService/NamingService_WaitForServerReadiness.cxx b/src/NamingService/NamingService_WaitForServerReadiness.cxx
new file mode 100644 (file)
index 0000000..b2ba19a
--- /dev/null
@@ -0,0 +1,96 @@
+//  Copyright (C) 2004  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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
+//
+//
+//
+//  File   : NamingService_WaitForServerReadiness.cxx
+//  Author : Paul RASCLE (EDF)
+//  Module : KERNEL
+//  $Header$
+
+#include "NamingService_WaitForServerReadiness.hxx"
+#include "utilities.h"
+#include <iostream>
+#include <ctime>
+
+using namespace std;
+
+// ============================================================================
+/*!
+ * Wait until a server is registered in naming service.
+ * \param serverName name of the server to find.
+ * \param NS SALOME_NamingService object
+ * Wait until the given server is ready i.e. is name is found in namingService.
+ * Try 40 times, with 250 ms sleep between each try.
+ * If Logger is used for traces, it must be ready before this call, because
+ * SALOME_NamingService client uses SALOME traces. So, Logger readiness must be
+ * checked in Launch script before execution of WaitForServerReadiness.
+ */
+// ============================================================================
+
+
+void NamingService_WaitForServerReadiness(SALOME_NamingService* NS,
+                                         string serverName)
+{
+  long TIMESleep = 250000000; // 250 ms.
+  int NumberOfTries = 40;     // total wait = 10 s.
+  int found = 0;
+
+  timespec ts_req;
+  ts_req.tv_nsec=TIMESleep;
+  ts_req.tv_sec=0;
+  timespec ts_rem;
+  ts_rem.tv_nsec=0;
+  ts_rem.tv_sec=0;
+
+  ASSERT(NS);
+  for (int itry=0; itry < NumberOfTries; itry++)
+    {
+      try
+       {
+         if (serverName.length() == 0)
+           {
+             string curdir = NS->Current_Directory(); // to wait for naming service
+             found = 1;
+             break; // naming service found
+           }
+         else
+           {
+             CORBA::Object_ptr obj = NS->Resolve(serverName.c_str());
+             if (! CORBA::is_nil(obj))
+               {
+                 found =1;
+                 break; // server found, no more try to do
+               }
+             MESSAGE("Server "<< serverName <<" not yet ready, waiting...");
+             int a = nanosleep(&ts_req,&ts_rem); // wait before retry
+           }
+       }
+      catch( ServiceUnreachable& )
+       {
+         MESSAGE("CORBA::COMM_FAILURE: Naming Service not yet ready, waiting...");
+         int a = nanosleep(&ts_req,&ts_rem); // wait before retry
+       }
+    }
+  if (!found)
+    {
+    INFOS("Server "<< serverName <<" not found, abort...");
+    exit(EXIT_FAILURE);
+    }
+}
diff --git a/src/NamingService/NamingService_WaitForServerReadiness.hxx b/src/NamingService/NamingService_WaitForServerReadiness.hxx
new file mode 100644 (file)
index 0000000..e656931
--- /dev/null
@@ -0,0 +1,36 @@
+//  Copyright (C) 2004  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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
+//
+//
+//
+//  File   : NamingService_WaitForServerReadiness.hxx
+//  Author : Paul RASCLE (EDF)
+//  Module : KERNEL
+//  $Header$
+
+#ifndef _NAMINGSERVICE_WAITFORSERVERREADINESS_HXX_
+#define _NAMINGSERVICE_WAITFORSERVERREADINESS_HXX_
+
+#include <string>
+#include "SALOME_NamingService.hxx"
+
+void NamingService_WaitForServerReadiness(SALOME_NamingService* NS,
+                                         std::string serverName);
+
+#endif
index 3e5a5b636fff0472744be2aa40614c9c3e77fced..51036654786859e09a261e2124dfbc65645049f4 100644 (file)
@@ -36,6 +36,7 @@ extern "C"
 }
 
 #include "utilities.h"
+#include "LocalTraceCollector.hxx"
 #include "Utils_ORB_INIT.hxx"
 #include "Utils_SINGLETON.hxx"
 #include "Utils_SALOME_Exception.hxx"
@@ -51,6 +52,9 @@ using namespace std;
 
 int main( int argc , char **argv )
 {
+  ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance() ;
+  CORBA::ORB_var &orb = init( argc , argv ) ;
+  LocalTraceCollector *myThreadTrace = LocalTraceCollector::instance(orb);
   BEGIN_OF( argv[0] )
     INFOS_COMPILATION 
     SCRUTE(argc) 
@@ -73,9 +77,6 @@ int main( int argc , char **argv )
   ASSERT(ptrSessionName) ;
   ASSERT(strlen( ptrSessionName )>0) ;
   const char *registryName = "Registry" ;
-  ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance() ;
-  CORBA::ORB_var &orb = init( argc , argv ) ;
-  //
   long TIMESleep = 250000000;
   int NumberOfTries = 40;
   int a;
@@ -210,5 +211,6 @@ int main( int argc , char **argv )
     }
        
   END_OF( argv[0] ) ;
+  delete myThreadTrace;
   return 0 ;
 }
index 56517030131e784cc8a7eba8475a512f42339300..d44450d9c5a4aea8e9daaaf95201c2bad3eb4f13 100755 (executable)
 
 #include "utilities.h"
 
+#include "SALOME_RessourcesCatalog_Handler.hxx"
+
+#include "utilities.h"
+
 using namespace std;
 
 ListOfParserressources _ressources_list;
index 4275a4924033c6b311a29dcd22bc92af805209cc..f8018d340dd3956f0caced2f7df376ae8e76487c 100644 (file)
 #include "SALOME_NamingService.hxx"
 #include "SALOME_RessourcesCatalog_impl.hxx"
 #include "utilities.h"
+#include "LocalTraceCollector.hxx"
 #include "Utils_SINGLETON.hxx"
 using namespace std;
 
 int main(int argc,char **argv)
 {
+  // initialize the ORB
+  CORBA::ORB_ptr orb = CORBA::ORB_init (argc, argv);
+  LocalTraceCollector *myThreadTrace = LocalTraceCollector::instance(orb);
   try
     {
       CosNaming::NamingContext_var _rootContext, catalogContext;
 
-      // initialize the ORB
-
-      CORBA::ORB_ptr orb = CORBA::ORB_init (argc, argv);
-
       // initialize POA
       //
       long TIMESleep = 250000000;
@@ -149,5 +149,6 @@ int main(int argc,char **argv)
     INFOS("Caught CORBA::Exception.")
       }
 
+  delete myThreadTrace;
   return 0;
 }
index 08990e6e5559658968c07892cc0ceea050e9097c..83ea5e0409656dc03b06ec4d864332f6f0becfb3 100644 (file)
@@ -10,6 +10,7 @@
 //  $Header$
 
 
+
 #include <string>
 #include <vector>
 
index 611b0e49bd26ac34794eee5de9013ddcdf007f6a..695f649194697fa413b0921ed57356365d378326 100644 (file)
@@ -12,6 +12,8 @@
 
 
 
+
+
 #include "QAD_PyInterp_mono.h"
 #include "utilities.h"
 
diff --git a/src/SALOMELocalTrace/LocalTraceBufferPool.cxx b/src/SALOMELocalTrace/LocalTraceBufferPool.cxx
new file mode 100644 (file)
index 0000000..73046c6
--- /dev/null
@@ -0,0 +1,217 @@
+//  Copyright (C) 2004  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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
+//
+//  Author : Paul RASCLE (EDF)
+//  Module : KERNEL
+//  $Header$
+//
+// Cf. C++ Users Journal, June 2004, Tracing Application Execution, Tomer Abramson
+//
+
+#include <iostream>
+#include <limits.h>
+
+#include "LocalTraceBufferPool.hxx"
+#include "utilities.h"
+
+// In case of truncated message, end of trace contains "...\n\0"
+#define TRUNCATED_MESSAGE "...\n"
+#define MAXMESS_LENGTH MAX_TRACE_LENGTH-5
+
+using namespace std;
+
+LocalTraceBufferPool* LocalTraceBufferPool::_singleton = 0;
+pthread_mutex_t LocalTraceBufferPool::_singletonMutex;
+
+// ============================================================================
+/*!
+ *  guarantees a unique object instance of the class (singleton thread safe)
+ */
+// ============================================================================
+
+LocalTraceBufferPool* LocalTraceBufferPool::instance()
+{
+  if (_singleton == 0) // no need of lock when singleton already exists
+    {
+      int ret;
+      ret = pthread_mutex_lock(&_singletonMutex); // acquire lock to be alone
+      if (_singleton == 0)                     // another thread may have got
+       {                                      // the lock after the first test
+         _singleton = new LocalTraceBufferPool(); 
+       }
+      ret = pthread_mutex_unlock(&_singletonMutex); // release lock
+    }
+  return _singleton;
+}
+
+// ============================================================================
+/*!
+ *  Called by trace producers within their threads. The trace message is copied
+ *  in specific buffer from a circular pool of buffers.
+ *  Waits until there is a free buffer in the pool, gets the first available
+ *  buffer, fills it with the message.
+ *  Messages are printed in a separate thread (see retrieve method)
+ */
+// ============================================================================
+
+int LocalTraceBufferPool::insert(int traceType, const char* msg)
+{
+
+  // get immediately a message number to control sequence (mutex protected)
+
+  unsigned long myMessageNumber = lockedIncrement(_position);
+
+  // wait until there is a free buffer in the pool
+
+  int ret = sem_wait(&_freeBufferSemaphore);
+
+  // get the next free buffer available (mutex protected) 
+
+  unsigned long myInsertPos = lockedIncrement(_insertPos);
+
+  // fill the buffer with message, thread id and type (normal or abort)
+
+  strncpy(_myBuffer[myInsertPos%TRACE_BUFFER_SIZE].trace,
+         msg,
+         MAXMESS_LENGTH); // last chars always "...\n\0" if msg too long
+  _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].threadId =pthread_self();//thread id
+  _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].traceType = traceType;
+  _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].position = myMessageNumber;
+
+
+  // increment the full buffer semaphore
+  // (if previously 0, awake thread in charge of trace)
+
+  ret = sem_post(&_fullBufferSemaphore);
+
+  // returns the number of free buffers
+
+  sem_getvalue(&_freeBufferSemaphore, &ret);
+  return ret;  
+}
+
+// ============================================================================
+/*!
+ *  Called by the thread in charge of printing trace messages.
+ *  Waits until there is a buffer with a message to print.
+ *  Gets the first buffer to print, copies it int the provided buffer
+ */
+// ============================================================================
+
+int LocalTraceBufferPool::retrieve(LocalTrace_TraceInfo& aTrace)
+{
+
+  // wait until there is a buffer in the pool, with a message to print
+
+  int ret = sem_wait(&_fullBufferSemaphore);
+
+  // get the next buffer to print
+
+  unsigned long myRetrievePos = lockedIncrement(_retrievePos);
+
+  // copy the buffer from the pool to the provided buffer
+
+  memcpy((void*)&aTrace,
+        (void*)&_myBuffer[myRetrievePos%TRACE_BUFFER_SIZE],
+        sizeof(aTrace));
+
+  // increment the free buffer semaphore
+  // (if previously 0, awake one of the threads waiting to put a trace, if any)
+  // there is no way to preserve the order of waiting threads if several
+  // threads are waiting to put a trace: the waken up thread is not
+  // necessarily the first thread to wait.
+
+  ret = sem_post(&_freeBufferSemaphore);
+
+  // returns the number of full buffers
+
+  sem_getvalue(&_fullBufferSemaphore, &ret);
+  return ret;
+}
+
+// ============================================================================
+/*!
+ *  Gives the number of buffers to print.
+ *  Usage : when the thread in charge of messages print id to be stopped,
+ *  check if there is still something to print, before stop.
+ *  There is no need of mutex here, provided there is only one thread to
+ *  retrieve and print the buffers.
+ */
+// ============================================================================
+
+unsigned long LocalTraceBufferPool::toCollect()
+{
+  return _insertPos - _retrievePos;
+}
+
+// ============================================================================
+/*!
+ * Constructor : initialize pool of buffers, semaphores and mutex.
+ */
+// ============================================================================
+
+LocalTraceBufferPool::LocalTraceBufferPool()
+{
+  //cout << "LocalTraceBufferPool::LocalTraceBufferPool()" << endl;
+
+  _insertPos   = ULONG_MAX;  // first increment will give 0
+  _retrievePos = ULONG_MAX;
+  _position=0;               // first message will have number = 1
+
+  memset(_myBuffer, 0, sizeof(_myBuffer)); // to guarantee end of strings = 0
+  for (int i=0; i<TRACE_BUFFER_SIZE; i++)
+    strcpy(&(_myBuffer[i].trace[MAXMESS_LENGTH]),TRUNCATED_MESSAGE);
+  int ret;
+  ret=sem_init(&_freeBufferSemaphore, 0, TRACE_BUFFER_SIZE); // all buffer free
+  if (ret!=0) IMMEDIATE_ABORT(ret);
+  ret=sem_init(&_fullBufferSemaphore, 0, 0);                 // 0 buffer full
+  if (ret!=0) IMMEDIATE_ABORT(ret);
+  ret=pthread_mutex_init(&_incrementMutex,NULL); // default = fast mutex
+  if (ret!=0) IMMEDIATE_ABORT(ret);
+}
+
+// ============================================================================
+/*!
+ * Destructor : release memory associated with semaphores and mutex
+ */
+// ============================================================================
+
+LocalTraceBufferPool::~LocalTraceBufferPool()
+{
+  int ret;
+  ret=sem_destroy(&_freeBufferSemaphore);
+  ret=sem_destroy(&_fullBufferSemaphore);
+  ret=pthread_mutex_destroy(&_incrementMutex);
+}
+
+// ============================================================================
+/*!
+ * pool counters are incremented under a mutex protection
+ */
+// ============================================================================
+
+unsigned long LocalTraceBufferPool::lockedIncrement(unsigned long& pos)
+{
+  int ret;
+  ret = pthread_mutex_lock(&_incrementMutex);   // lock access to counters
+  pos++;
+  ret = pthread_mutex_unlock(&_incrementMutex); // release lock
+  return pos;
+}
+
diff --git a/src/SALOMELocalTrace/LocalTraceBufferPool.hxx b/src/SALOMELocalTrace/LocalTraceBufferPool.hxx
new file mode 100644 (file)
index 0000000..597b218
--- /dev/null
@@ -0,0 +1,71 @@
+//  Copyright (C) 2004  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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
+//
+//  Author : Paul RASCLE (EDF)
+//  Module : KERNEL
+//  $Header$
+
+#ifndef _LOCALTRACEBUFFERPOOL_HXX_
+#define _LOCALTRACEBUFFERPOOL_HXX_
+
+#define TRACE_BUFFER_SIZE 256  // number of entries in circular buffer
+                               // must be power of 2
+#define MAX_TRACE_LENGTH 256   // messages are truncated at this size
+
+#include <pthread.h>
+#include <semaphore.h>
+
+#define ABORT_MESS  1   // for traceType field in struct LocalTrace_TraceInfo
+#define NORMAL_MESS 0
+
+struct LocalTrace_TraceInfo
+{
+  char trace[MAX_TRACE_LENGTH];
+  pthread_t threadId;
+  int traceType;                 // normal or abort
+  int position;                  // to check sequence
+};
+
+class LocalTraceBufferPool
+{
+ public:
+  static LocalTraceBufferPool* instance();
+  int insert(int traceType, const char* msg);
+  int retrieve(LocalTrace_TraceInfo& aTrace);
+  unsigned long toCollect();
+  ~LocalTraceBufferPool();
+
+ protected:
+  LocalTraceBufferPool();
+  unsigned long lockedIncrement(unsigned long& pos);
+
+ private:
+  static LocalTraceBufferPool* _singleton;
+  static pthread_mutex_t _singletonMutex;
+  LocalTrace_TraceInfo _myBuffer[TRACE_BUFFER_SIZE];
+  sem_t _freeBufferSemaphore;       // to wait until there is a free buffer
+  sem_t _fullBufferSemaphore;       // to wait until there is a buffer to print
+  pthread_mutex_t _incrementMutex;  // to lock position variables for increment
+  unsigned long _position;
+  unsigned long _insertPos;
+  unsigned long _retrievePos;
+  pthread_t _threadId;
+};
+
+#endif
diff --git a/src/SALOMELocalTrace/LocalTraceCollector.cxx b/src/SALOMELocalTrace/LocalTraceCollector.cxx
new file mode 100644 (file)
index 0000000..0cb334b
--- /dev/null
@@ -0,0 +1,278 @@
+//  Copyright (C) 2004  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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
+//
+//
+//
+//  File   : LocalTraceCollector.cxx
+//  Author : Paul RASCLE (EDF)
+//  Module : KERNEL
+//  $Header$
+
+#include <iostream>
+#include <sstream>
+#include <fstream>
+#include <cstdlib>
+#include <CORBA.h>
+
+using namespace std;
+
+#include "LocalTraceCollector.hxx"
+#include "LocalTrace_WaitForServerReadiness.hxx"
+//#include "SALOME_Log.hxx"
+#include <SALOMEconfig.h>
+#include CORBA_CLIENT_HEADER(Logger)
+
+// Class attributes initialisation, for class method LocalTraceCollector::run
+
+LocalTraceCollector* LocalTraceCollector::_singleton = 0;
+pthread_mutex_t LocalTraceCollector::_singletonMutex;
+int LocalTraceCollector::_threadToClose = 0;
+pthread_t LocalTraceCollector::_threadId = 0; // used to control single run
+int LocalTraceCollector::_toFile = 0;
+std::string LocalTraceCollector::_fileName = "";
+CORBA::ORB_ptr LocalTraceCollector::_orb = 0;
+
+// ============================================================================
+/*!
+ *  guarantees a unique object instance of the class (singleton thread safe)
+ *  a separate thread for loop to print traces is launched.
+ *  \param typeTrace 0=standard out, 1=file(/tmp/tracetest.log), 2=CORBA log
+ *  If typeTrace=0, checks environment for "SALOME_trace". Test values in
+ *  the following order:
+ *  - "local"  standard out
+ *  - "with_logger" CORBA log
+ *  - anything else is kept as a file name
+ */
+// ============================================================================
+
+LocalTraceCollector* LocalTraceCollector::instance(CORBA::ORB_ptr theOrb,
+                                                  int typeTrace)
+{
+  if (_singleton == 0) // no need of lock when singleton already exists
+    {
+      int ret;
+      ret = pthread_mutex_lock(&_singletonMutex); // acquire lock to be alone
+      if (_singleton == 0)                     // another thread may have got
+       {                                      // the lock after the first test
+         _singleton = new LocalTraceCollector();
+
+         _fileName = "/tmp/tracetest.log";
+         _toFile=0;
+         _orb = theOrb;
+         if (typeTrace)       // caller sets a value different from default=0
+           _toFile = typeTrace; 
+         else                 // check environment
+           {
+             char* traceKind = getenv("SALOME_trace");
+             //cout<<"SALOME_trace="<<traceKind<<endl;
+             if (traceKind)
+               {
+                 if (strcmp(traceKind,"local")==0) _toFile=0;
+                 else if (strcmp(traceKind,"with_logger")==0) _toFile=2;
+                 else
+                   {
+                     _toFile=1;
+                     _fileName = traceKind;
+                   }       
+               }
+           }
+         //cout <<"_toFile: "<<_toFile<<" _fileName: "<<_fileName<<endl;
+
+         pthread_t traceThread;
+         int bid;
+         int re2 = pthread_create(&traceThread, NULL,
+                                  LocalTraceCollector::run, (void *)bid);
+       }
+      ret = pthread_mutex_unlock(&_singletonMutex); // release lock
+    }
+  return _singleton;
+}
+
+// ============================================================================
+/*!
+ *  In a separate thread, loop to print traces.
+ *  Mutex garantees intialisation on instance method is done and only one run
+ *  allowed (double check ...)
+ *  Loop until there is no more buffer to print,
+ *  and no ask for end from destructor.
+ *  Get a buffer. If type = ABORT then exit application with message.
+ */
+// ============================================================================
+
+void* LocalTraceCollector::run(void *bid)
+{
+  int isOKtoRun = 0;
+  int ret = pthread_mutex_lock(&_singletonMutex); // acquire lock to be alone
+  if (! _threadId)  // only one run
+    {
+      isOKtoRun = 1;
+      _threadId = pthread_self();
+    }
+  else cout << "----- Comment est-ce possible de passer la ? -------" <<endl;
+  ret = pthread_mutex_unlock(&_singletonMutex); // release lock
+
+  if (isOKtoRun)
+    { 
+      _threadId = pthread_self();
+      LocalTraceBufferPool* myTraceBuffer = LocalTraceBufferPool::instance();
+      LocalTrace_TraceInfo myTrace;
+
+      // if trace in file requested, opens a file with append mode
+      // so, several processes can share the same file
+      // if CORBA collection requested, wait for Logger server readiness
+
+      ofstream traceFile;
+      SALOME_Logger::Logger_var m_pInterfaceLogger;
+      CORBA::Object_var obj;
+
+      switch (_toFile)
+       {
+       case 1 :  // --- trace to file
+         {
+           const char *fileName = _fileName.c_str();
+           traceFile.open(fileName, ios::out | ios::app);
+           if (!traceFile)
+             {
+               cerr << "impossible to open trace file "<< fileName << endl;
+               exit (1);
+             }
+         }
+         break;
+       case 2 :  // --- trace collection via CORBA
+         obj = LocalTrace_WaitForServerReadiness(_orb,"Logger");
+         if (!CORBA::is_nil(obj))
+           m_pInterfaceLogger = SALOME_Logger::Logger::_narrow(obj);
+         if (CORBA::is_nil(m_pInterfaceLogger))
+           {
+             cerr << "Logger server not found ! Abort" << endl;
+             cerr << flush ; 
+             exit(1);
+           } 
+         else
+           {
+             CORBA::String_var LogMsg =
+               CORBA::string_dup("\n---Init logger trace---\n");
+             m_pInterfaceLogger->putMessage(LogMsg);
+             //cout << " Logger server found" << endl;
+           }
+         break;
+       case 0 : ; // --- trace to standard output
+       default :  // --- on standard output, too
+         break;
+       }
+
+      // Loop until there is no more buffer to print,
+      // and no ask for end from destructor.
+
+      while ((!_threadToClose) || myTraceBuffer->toCollect() )
+       {
+         int fullBuf = myTraceBuffer->retrieve(myTrace);
+         if (myTrace.traceType == ABORT_MESS)
+           {
+             switch (_toFile)
+               {
+               case 2 :  // --- trace collection via CORBA
+                 {
+                   stringstream abortMessage("");
+                   abortMessage << "INTERRUPTION from thread "
+                                << myTrace.threadId << " : " << myTrace.trace;
+                   CORBA::String_var LogMsg =
+                     CORBA::string_dup(abortMessage.str().c_str());
+                   m_pInterfaceLogger->putMessage(LogMsg);
+                   exit(1);
+                 }
+                 break;
+               case 1 :  // --- trace to file
+                 traceFile << "INTERRUPTION from thread " << myTrace.threadId
+                           << " : " <<  myTrace.trace;
+                 traceFile.close();
+                 // no break here !
+               case 0 :  // --- trace to standard output
+               default : // --- on standard output, too
+                 cout << flush ;
+                 cerr << "INTERRUPTION from thread " << myTrace.threadId
+                      << " : " <<  myTrace.trace;
+                 cerr << flush ; 
+                 exit(1);     
+                 break;
+               }
+           }
+         else
+           {
+             switch (_toFile)
+               {
+               case 2 :  // --- trace collection via CORBA
+                 {
+                   stringstream aMessage("");
+                   aMessage << "th. " << myTrace.threadId
+                            << " " << myTrace.trace;
+                   CORBA::String_var LogMsg =
+                     CORBA::string_dup(aMessage.str().c_str());
+                   m_pInterfaceLogger->putMessage(LogMsg);
+                 }
+                 break;
+               case 1 :  // --- trace to file
+                 traceFile << "th. " << myTrace.threadId
+                           << " " << myTrace.trace;
+                 break;
+               case 0 :  // --- trace to standard output
+               default : // --- on standard output, too
+                 cout << "th. " << myTrace.threadId << " " << myTrace.trace;
+                 break;
+               }
+           }
+       }
+
+      if (_toFile==1) traceFile.close();
+    }
+  pthread_exit(NULL);
+}
+
+// ============================================================================
+/*!
+ *  Destructor: wait until printing thread ends (LocalTraceCollector::run)
+ */
+// ============================================================================
+
+LocalTraceCollector:: ~LocalTraceCollector()
+{
+  _threadToClose = 1;
+  if (_threadId)
+    {
+      int ret = pthread_join(_threadId, NULL);
+      if (ret) cout << "error close LocalTraceCollector : "<< ret << endl;
+      else cout << "LocalTraceCollector destruction OK" << endl;
+    }
+  LocalTraceBufferPool* myTraceBuffer = LocalTraceBufferPool::instance();
+  delete myTraceBuffer;
+}
+
+// ============================================================================
+/*!
+ * Constructor: no need of LocalTraceBufferPool object initialization here,
+ * thread safe singleton used in LocalTraceBufferPool::instance()
+ */
+// ============================================================================
+
+LocalTraceCollector::LocalTraceCollector()
+{
+  _threadId=0;
+}
+
+
diff --git a/src/SALOMELocalTrace/LocalTraceCollector.hxx b/src/SALOMELocalTrace/LocalTraceCollector.hxx
new file mode 100644 (file)
index 0000000..90101ef
--- /dev/null
@@ -0,0 +1,54 @@
+//  Copyright (C) 2004  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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
+//
+//
+//
+//  File   : LocalTraceCollector.hxx
+//  Author : Paul RASCLE (EDF)
+//  Module : KERNEL
+//  $Header$
+
+#ifndef _LOCALTRACECOLLECTOR_HXX_
+#define _LOCALTRACECOLLECTOR_HXX_
+
+#include <string>
+#include <CORBA.h>
+#include "LocalTraceBufferPool.hxx"
+
+class LocalTraceCollector
+{
+ public:
+  static LocalTraceCollector* instance(CORBA::ORB_ptr theOrb, int typeTrace=0);
+  static void *run(void *bid);
+  ~LocalTraceCollector();
+
+ protected:
+  LocalTraceCollector();
+
+ private:
+  static int _threadToClose;
+  static int _toFile;
+  static LocalTraceCollector* _singleton;
+  static pthread_mutex_t _singletonMutex;
+  static pthread_t _threadId;
+  static std::string _fileName;
+  static CORBA::ORB_ptr _orb;
+};
+
+#endif
diff --git a/src/SALOMELocalTrace/LocalTrace_WaitForServerReadiness.cxx b/src/SALOMELocalTrace/LocalTrace_WaitForServerReadiness.cxx
new file mode 100644 (file)
index 0000000..75a0952
--- /dev/null
@@ -0,0 +1,131 @@
+//  Copyright (C) 2004  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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
+//
+//
+//
+//  File   : LocalTrace_WaitForServerReadiness.cxx
+//  Author : Paul RASCLE (EDF)
+//  Module : KERNEL
+//  $Header$
+
+#include "LocalTrace_WaitForServerReadiness.hxx"
+#include <iostream>
+#include <ctime>
+
+using namespace std;
+
+// ============================================================================
+/*!
+ *  Wait until a server is registered in naming service.
+ *  \param serverName name of the server to find.
+ *  When SALOME_NamingService is available,
+ *  use NamingService_WaitForServerReadiness instead.
+ *  This function is needed when macro MESSAGE used by SALOME_NamingService
+ *  is not available (inside LocalTrace methods, for instance !).
+ *  Direct access to CORBA Name Service. Look for serverName at Name service
+ *  Root without extensions.
+ */
+// ============================================================================
+
+CORBA::Object_ptr LocalTrace_WaitForServerReadiness(CORBA::ORB_ptr orb,
+                                                   string serverName)
+{
+  long TIMESleep = 250000000;
+  int NumberOfTries = 40;
+
+  timespec ts_req;
+  ts_req.tv_nsec=TIMESleep;
+  ts_req.tv_sec=0;
+  timespec ts_rem;
+  ts_rem.tv_nsec=0;
+  ts_rem.tv_sec=0;
+
+  CORBA::Object_var obj;
+
+  try
+    {
+      // NB. You can't use SALOME_NamingService class because
+      // it uses MESSAGE macro
+      // Otherwise, you will get segmentation fault.   
+
+      CosNaming::NamingContext_var inc;
+      CosNaming::Name name;
+      name.length(1);
+      name[0].id = CORBA::string_dup(serverName.c_str());
+      CORBA::Object_var theObj;
+
+      for (int itry=0; itry < NumberOfTries; itry++)
+       {
+         try
+           { 
+             if(!CORBA::is_nil(orb)) 
+               theObj = orb->resolve_initial_references("NameService");
+             if (!CORBA::is_nil(theObj))
+               inc = CosNaming::NamingContext::_narrow(theObj);
+           }  
+         catch( CORBA::COMM_FAILURE& )
+           {
+             cout << "LocalTrace_WaitForServerReadiness: "
+                  << "CORBA::COMM_FAILURE: "
+                  << "Unable to contact the Naming Service" << endl;
+           }
+          catch(...)
+           {
+             cout << "LocalTrace_WaitForServerReadiness: "
+                  << "Unknown exception dealing with Naming Service" << endl;
+           }
+         
+         if(!CORBA::is_nil(inc))
+           {
+             obj = inc->resolve(name);
+             if (!CORBA::is_nil(obj))
+               {
+                 cout << "LocalTrace_WaitForServerReadiness: "
+                      << serverName << " found in CORBA Name Service" << endl;
+                 break;
+               }
+           }
+         int a = nanosleep(&ts_req,&ts_rem);
+         cout << "LocalTrace_WaitForServerReadiness: retry look for"
+              << serverName << endl;
+       }          
+    }
+  catch (const CosNaming::NamingContext::NotFound&)
+    {
+      cout << "Caught exception: Naming Service can't found Logger";
+    }
+  catch (CORBA::COMM_FAILURE&)
+    {
+      cout << "Caught CORBA::SystemException CommFailure.";
+    }
+  catch (CORBA::SystemException&)
+    {
+      cout << "Caught CORBA::SystemException.";
+    }
+  catch (CORBA::Exception&)
+    {
+      cout << "Caught CORBA::Exception.";
+    }
+  catch (...)
+    {
+      cout << "Caught unknown exception.";
+    }
+  return obj._retn();
+}
+
diff --git a/src/SALOMELocalTrace/LocalTrace_WaitForServerReadiness.hxx b/src/SALOMELocalTrace/LocalTrace_WaitForServerReadiness.hxx
new file mode 100644 (file)
index 0000000..a5e1c9a
--- /dev/null
@@ -0,0 +1,36 @@
+//  Copyright (C) 2004  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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
+//
+//
+//
+//  File   : LocalTrace_WaitForServerReadiness.hxx
+//  Author : Paul RASCLE (EDF)
+//  Module : KERNEL
+//  $Header$
+
+#ifndef _LOCALTRACE_WAITFORSERVERREADINESS_HXX_
+#define _LOCALTRACE_WAITFORSERVERREADINESS_HXX_
+
+#include <CORBA.h> 
+#include <string>
+
+CORBA::Object_ptr  LocalTrace_WaitForServerReadiness(CORBA::ORB_ptr theOrb,
+                                                    std::string serverName);
+
+#endif
index 6e3674a3eb5149978c39e54820cc49086dc33c24..5928c6409a25da56f2e84762c815565b6f1e37b3 100644 (file)
@@ -35,15 +35,21 @@ VPATH=.:@srcdir@:@top_srcdir@/idl
 @COMMENCE@
 
 # header files  
-EXPORT_HEADERS= SALOME_Log.hxx
+EXPORT_HEADERS= utilities.h \
+               LocalTraceBufferPool.hxx \
+               LocalTraceCollector.hxx \
+               LocalTrace_WaitForServerReadiness.hxx
 
 EXPORT_PYSCRIPTS = 
 
 # Libraries targets
 
 LIB = libSALOMELocalTrace.la 
-LIB_SRC = SALOME_Log.cxx
+LIB_SRC = LocalTraceCollector.cxx \
+         LocalTraceBufferPool.cxx \
+         LocalTrace_WaitForServerReadiness.cxx
 
+LIB_CLIENT_IDL = Logger.idl 
 LDFLAGS+= 
 
 @CONCLUDE@
diff --git a/src/SALOMELocalTrace/utilities.h b/src/SALOMELocalTrace/utilities.h
new file mode 100644 (file)
index 0000000..94543b9
--- /dev/null
@@ -0,0 +1,124 @@
+//  SALOME Utils : general SALOME's definitions and tools
+//
+//  Copyright (C) 2003  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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
+//
+//
+//
+//  File   : utilities.h
+//  Author : Antoine YESSAYAN, Paul RASCLE, EDF
+//  Module : SALOME
+//  $Header$
+
+/* ---  Definition macros file to print informations if _DEBUG_ is defined --- */
+
+#ifndef UTILITIES_H
+#define UTILITIES_H
+
+#include <strstream>
+#include <iostream>
+#include <sstream>
+#include <cstdlib>
+
+using namespace std;
+
+#include "LocalTraceBufferPool.hxx"
+
+/*!
+ * For each message to put in the trace, a specific ostingstream object is
+ * created and destroyed automatically at the end of the message macro.
+ * The insert function of LocalTraceBufferPool class gets a buffer in a
+ * buffer pool (unique with the help of mutexes and semaphores) and copy the
+ * message in the buffer.
+ * This buffer is read later by a specific thread in charge of trace print.
+ * Order of trace entries is globally respected. Nevertheless, if there are
+ * several threads waiting for a free buffer to trace, the order of
+ * thread waken up is not garanteed (no fifo or priority rules in Linux Kernel)
+ */
+
+#define MESS_INIT(deb) ostringstream os; os<<deb
+#define MESS_BEGIN(deb) MESS_INIT(deb)<<__FILE__ <<" ["<<__LINE__<<"] : "
+#define MESS_END endl; LocalTraceBufferPool::instance()->insert(NORMAL_MESS, os.str().c_str());
+#define MESS_ABORT endl; LocalTraceBufferPool::instance()->insert(ABORT_MESS, os.str().c_str());
+
+// --- Some macros are always defined (without _DEBUG_): for use with release version
+
+#define INFOS(msg) {MESS_BEGIN("- Trace ") << msg << MESS_END}
+#define PYSCRIPT(msg) {MESS_INIT("---PYSCRIPT--- ") << msg << MESS_END}
+#define INTERRUPTION(msg) {MESS_BEGIN("- INTERRUPTION: ")<< msg << MESS_ABORT}
+#define IMMEDIATE_ABORT(code) {cout <<flush; \
+                               cerr << "- ABORT " << __FILE__ << " [" <<__LINE__<< "] : " << flush; \
+                               cerr << "ABORT return code= "<< code << endl; \
+                               std::exit(code);}
+
+/* --- To print date and time of compilation of current source --- */
+
+#if defined ( __GNUC__ )
+#define COMPILER               "g++" 
+#elif defined ( __sun )
+#define COMPILER               "CC" 
+#elif defined ( __KCC )
+#define COMPILER               "KCC" 
+#elif defined ( __PGI )
+#define COMPILER               "pgCC" 
+#elif defined ( __alpha )
+#define COMPILER               "cxx" 
+#else
+#define COMPILER               "undefined" 
+#endif
+
+#ifdef INFOS_COMPILATION
+#error INFOS_COMPILATION already defined
+#endif
+
+#define INFOS_COMPILATION { MESS_BEGIN("COMPILED with ") << COMPILER \
+                                      << ", " << __DATE__ \
+                                      << " at " << __TIME__ << MESS_END }
+#ifdef _DEBUG_
+
+// --- the following MACROS are useful at debug time
+
+#define MESSAGE(msg) {MESS_BEGIN("- Trace ") << msg << MESS_END}
+#define SCRUTE(var)  {MESS_BEGIN("- Trace ") << #var << "=" << var <<MESS_END}
+
+#define REPERE ("------- ")
+#define BEGIN_OF(msg) {MESS_BEGIN(REPERE) << "Begin of: "      << msg << MESS_END} 
+#define END_OF(msg)   {MESS_BEGIN(REPERE) << "Normal end of: " << msg << MESS_END} 
+
+#ifndef ASSERT
+#define ASSERT(condition) \
+        if (!(condition)){INTERRUPTION("CONDITION "<<#condition<<" NOT VERIFIED")}
+#endif /* ASSERT */
+
+
+#else /* ifdef _DEBUG_*/
+
+#define MESSAGE(msg) {}
+#define SCRUTE(var) {}
+#define REPERE
+#define BEGIN_OF(msg) {}
+#define END_OF(msg) {}
+
+#ifndef ASSERT
+#define ASSERT(condition) {}
+#endif /* ASSERT */
+
+#endif /* ifdef _DEBUG_*/
+
+#endif /* ifndef UTILITIES_H */
diff --git a/src/SALOMELogger/Makefile.in b/src/SALOMELogger/Makefile.in
deleted file mode 100644 (file)
index 2a9f4f5..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-#  SALOMELogger : CORBA distributed log
-#
-#  Copyright (C) 2003  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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
-#
-#
-#
-#  File   : Makefile.in
-#  Author : Paul RASCLE (EDF)
-#  Module : SALOME
-#  $Header$
-
-top_srcdir=@top_srcdir@
-top_builddir=../..
-srcdir=@srcdir@
-VPATH=.:@srcdir@:@top_srcdir@/idl
-
-
-@COMMENCE@
-
-# header files  
-EXPORT_HEADERS= 
-
-EXPORT_PYSCRIPTS = 
-
-# Libraries targets
-
-LIB = libSALOMELoggerClient.la 
-LIB_SRC = SALOME_LoggerClient.cxx
-LIB_CLIENT_IDL = Logger.idl 
-
-LDFLAGS+= 
-
-@CONCLUDE@
diff --git a/src/SALOMELogger/SALOME_LoggerClient.cxx b/src/SALOMELogger/SALOME_LoggerClient.cxx
deleted file mode 100644 (file)
index d876a73..0000000
+++ /dev/null
@@ -1,156 +0,0 @@
-//  SALOME_LoggerClient : CORBA distributed log
-//
-//  Copyright (C) 2003  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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
-//
-//
-//
-//  File   : SALOME_Loggerclient.hxx
-//  Author : Vasily Rusyaev, Paul RASCLE, EDF
-//  Module : KERNEL
-//  $Header$
-
-#include <string>
-#include <iostream>
-
-using namespace std;
-
-#include "SALOME_Log.hxx"
-
-#include <SALOMEconfig.h>
-#include CORBA_CLIENT_HEADER(Logger)
-
-#include "utilities.h"
-
-// class SALOME_LoggerClient : public SALOME_Log
-// {
-// protected:
-//   SALOME_Logger::Logger_var m_pInterfaceLogger; // object reference on Logger server
-// };
-
-SALOME_Logger::Logger_ptr m_pInterfaceLogger; // object reference on Logger server
-
-SALOME_Log::SALOME_Log()
-{
-  MESSAGE("SALOME_LoggerClient: constructor");
-  //get reference on object reference from NS
-  //and initialize m_pInterfaceLogger 
-
-  int argc = 1;
-  char* argv[1] = {"application"};
-  try
-    {
-      //NB. You can't use SALOME_NamingService class because it uses MESSAGE macro
-      //Otherwise, you will get segmentation fault.   
-
-      //Initialize the ORB
-      CORBA::ORB_var orb = CORBA::ORB_init(argc,argv);
-      long TIMESleep = 250000000;
-      int NumberOfTries = 40;
-      int a;
-      timespec ts_req;
-      ts_req.tv_nsec=TIMESleep;
-      ts_req.tv_sec=0;
-      timespec ts_rem;
-      ts_rem.tv_nsec=0;
-      ts_rem.tv_sec=0;
-      CosNaming::NamingContext_var inc;
-      CORBA::Object_var theObj;
-      CORBA::Object_var obj;
-      CosNaming::Name name;
-      name.length(1);
-      name[0].id = CORBA::string_dup("Logger");
-      for (int i = 1; i<=NumberOfTries; i++)
-       {
-         if (i!=1) 
-           a=nanosleep(&ts_req,&ts_rem);
-         try
-           { 
-             if(!CORBA::is_nil(orb)) 
-               theObj = orb->resolve_initial_references("NameService");
-             if (!CORBA::is_nil(theObj))
-               inc = CosNaming::NamingContext::_narrow(theObj);
-           }  
-         catch( CORBA::COMM_FAILURE& )
-           {
-             MESSAGE("SALOME_LoggerClient: CORBA::COMM_FAILURE: Unable to contact the Naming Service");
-           }
-          catch(...)
-           {
-             MESSAGE("SALOME_LoggerClient: Unknown exception dealing with Naming Service");
-           }
-         
-         if(!CORBA::is_nil(inc))
-           {
-             obj = inc->resolve(name);
-             m_pInterfaceLogger = SALOME_Logger::Logger::_narrow(obj);
-             if (!CORBA::is_nil(m_pInterfaceLogger))
-               MESSAGE("SALOME_LoggerClient: Logger Server was found");
-             break;
-           }
-       }          
-    }
-  catch (const CosNaming::NamingContext::NotFound&)
-    {
-      //       MESSAGE("Caught exception: Naming Service can't found Logger");
-    }
-  catch (CORBA::COMM_FAILURE&)
-    {
-      //       MESSAGE("Caught CORBA::SystemException CommFailure.");
-    }
-  catch (CORBA::SystemException&)
-    {
-      //       MESSAGE("Caught CORBA::SystemException.");
-    }
-  catch (CORBA::Exception&)
-    {
-      //       MESSAGE("Caught CORBA::Exception.");
-    }
-  catch (...)
-    {
-      //       MESSAGE("Caught unknown exception.");
-    }
-  //cerr << "-----SALOME_Trace::SALOME_Trace----"<<endl;
-}
-
-SALOME_Log::~SALOME_Log()
-{
-}
-
-SALOME_Log& SALOME_Log::Instance()
-{
-  static SALOME_Log instance;
-  return instance;
-}
-
-void SALOME_Log::putMessage(std::ostream& msg)
-{
-  //write resulting string into Logger CORBA server
-
-  char* adt = str();
-  CORBA::String_var LogMsg = CORBA::string_dup(adt);
-  rdbuf()->freeze(false);
-  seekp(0);
-
-  if (CORBA::is_nil(m_pInterfaceLogger))
-    cout << LogMsg << std::flush;
-  else
-    m_pInterfaceLogger-> putMessage (LogMsg) ;
- }
-
index cd9060a3ccadc043b4b5ef4632bfad463e5442a9..2a8522145276c90c9c6449359ab1951f638ffa23 100644 (file)
@@ -55,6 +55,7 @@
 #include CORBA_SERVER_HEADER(SALOMEDS)
 
 #include "utilities.h"
+#include "LocalTraceCollector.hxx"
 
 #include "SALOME_Session_i.hxx"
 
@@ -90,15 +91,13 @@ static int MYDEBUG = 0;
 
 int main(int argc, char **argv)
 {
+  SALOME_Event::GetSessionThread();
+  ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance() ;
+  int orbArgc = 1;
+  CORBA::ORB_var &orb = init( orbArgc , argv ) ;
+  LocalTraceCollector *myThreadTrace = LocalTraceCollector::instance(orb);
   try
     {
-      SALOME_Event::GetSessionThread();
-
-      ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance() ;
-      ASSERT(SINGLETON_<ORB_INIT>::IsAlreadyExisting()) ;
-      int orbArgc = 1;
-      CORBA::ORB_var &orb = init( orbArgc , argv ) ;
-
       CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
       PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
 
@@ -253,5 +252,7 @@ int main(int argc, char **argv)
     {
       INFOS("Caught unknown exception.");
     }
+  MESSAGE("End of SALOME_Session_Server");
+  delete myThreadTrace;
   return 0 ;
 }
index be3f1a4f22b5dfd688ce4889073aabb394c6a92a..886aef9b903390e66d89c6e244e36a38a021ff15 100644 (file)
@@ -42,6 +42,7 @@
 #include "Utils_SINGLETON.hxx"
 #include "Utils_SALOME_Exception.hxx"
 #include "OpUtil.hxx"
+#include "NamingService_WaitForServerReadiness.hxx"
 #include "utilities.h"
 
 #include <cstdlib>
@@ -56,64 +57,6 @@ const char* Session_ServerThread::_serverTypes[NB_SRV_TYP] = {"Container",
                                                              "SALOMEDS",
                                                              "Session"};
 
-//=============================================================================
-/*! 
- * Wait until the given server is ready i.e. is name is found in namingService.
- * Try 40 times, with 250 ms sleep between each try.
- * If Logger is used for traces, it must be ready before this call, because
- * SALOME_NamingService client uses SALOME traces. So, Logger readiness must be
- * checked in Launch script before execution of WaitForServerReadiness.
- */
-//=============================================================================
-
-void WaitForServerReadiness(SALOME_NamingService* NS, string serverName)
-{
-  long TIMESleep = 250000000; // 250 ms.
-  int NumberOfTries = 40;     // total wait = 10 s.
-  int found = 0;
-
-  timespec ts_req;
-  ts_req.tv_nsec=TIMESleep;
-  ts_req.tv_sec=0;
-  timespec ts_rem;
-  ts_rem.tv_nsec=0;
-  ts_rem.tv_sec=0;
-
-  for (int itry=0; itry < NumberOfTries; itry++)
-    {
-      try
-       {
-         if (serverName.length() == 0)
-           {
-             string curdir = NS->Current_Directory(); // to wait for naming service
-             found = 1;
-             break; // naming service found
-           }
-         else
-           {
-             CORBA::Object_ptr obj = NS->Resolve(serverName.c_str());
-             if (! CORBA::is_nil(obj))
-               {
-                 found =1;
-                 break; // server found, no more try to do
-               }
-             MESSAGE("Server "<< serverName <<" not yet ready, waiting...");
-             int a = nanosleep(&ts_req,&ts_rem); // wait before retry
-           }
-       }
-      catch( ServiceUnreachable& )
-       {
-         MESSAGE("CORBA::COMM_FAILURE: Naming Service not yet ready, waiting...");
-         int a = nanosleep(&ts_req,&ts_rem); // wait before retry
-       }
-    }
-  if (!found)
-    {
-    INFOS("Server "<< serverName <<" not found, abort...");
-    exit(EXIT_FAILURE);
-    }
-}
-
 //=============================================================================
 /*! 
  *  default constructor not for use
@@ -180,35 +123,35 @@ void Session_ServerThread::Init()
          {
          case 0:  // Container
            {
-             WaitForServerReadiness(_NS,"/Registry");
+             NamingService_WaitForServerReadiness(_NS,"/Registry");
              ActivateContainer(_argc, _argv);
              break;
            }
          case 1:  // ModuleCatalog
            {
-             WaitForServerReadiness(_NS,"/Registry");
+             NamingService_WaitForServerReadiness(_NS,"/Registry");
              ActivateModuleCatalog(_argc, _argv);
              break;
            }
          case 2:  // Registry
            {
-             WaitForServerReadiness(_NS,"");
+             NamingService_WaitForServerReadiness(_NS,"");
              ActivateRegistry(_argc, _argv);
              break;
            }
          case 3:  // SALOMEDS
            {
-             WaitForServerReadiness(_NS,"/Kernel/ModulCatalog");
+             NamingService_WaitForServerReadiness(_NS,"/Kernel/ModulCatalog");
              ActivateSALOMEDS(_argc, _argv);
              break;
            }
          case 4:  // Session
            {
-             WaitForServerReadiness(_NS,"/myStudyManager");
+             NamingService_WaitForServerReadiness(_NS,"/myStudyManager");
              string containerName = "/Containers/";
              containerName = containerName + GetHostname();
              containerName = containerName + "/FactoryServer";
-             WaitForServerReadiness(_NS,containerName);
+             NamingService_WaitForServerReadiness(_NS,containerName);
              ActivateSession(_argc, _argv);
              break;
            }
index 73737cb457a254611086f440428c4c5411932e4f..b7dfc2c865dba2d774ed9033b4f0dfb2e8763aba 100644 (file)
@@ -37,9 +37,6 @@
 
 using namespace std;
 
-void WaitForServerReadiness(string serverName);
-
-
 class Session_ServerThread
 {
 public:
index b320657b137c011e575de286dd426b7f6130037f..f7f5d5a65967114fb023744f0f9ac1d999402cd5 100644 (file)
@@ -36,7 +36,6 @@ VPATH=.:@srcdir@:@top_srcdir@/idl
 
 # header files  
 EXPORT_HEADERS= \
-       utilities.h \
        OpUtil.hxx \
        Utils_Timer.hxx \
        Utils_CorbaException.hxx \
index b1e449ce43cf414ee4fa2cce87ca4f801c6c48f1..fa6cff73770f45f7f4b0946588875c67e4af7b15 100644 (file)
  *     It is strongly (and only) used in the Registry environment
  *     (RegistryService, RegistryConnexion, Identity, ...)
  */
-extern "C"
-{
-#include <stdlib.h>
-#include <string.h>
-}
+
+#include <cstdlib>
+#include <cstring>
+
 #include  "utilities.h"
 
 using namespace std;