From 8d381f95c9df11c395291909012a9ee263810493 Mon Sep 17 00:00:00 2001 From: prascle Date: Fri, 5 Nov 2004 15:54:41 +0000 Subject: [PATCH] PR: mergefrom_PRAS_br3_06Nov04 --- bin/runSalome.py | 838 +++++++++++------- src/Container/SALOME_Container.cxx | 18 +- .../SALOME_DataTypeCatalog_Handler.cxx | 4 + .../SALOME_DataTypeCatalog_Server.cxx | 7 +- src/Loader/InquireServersQThread.cxx | 5 +- src/Loader/SALOME_Session_Loader.cxx | 11 +- src/MPIContainer/SALOME_MPIContainer.cxx | 4 + src/Makefile.in | 2 +- .../SALOME_ModuleCatalog_Server.cxx | 9 +- src/NamingService/Makefile.in | 9 +- .../NamingService_WaitForServerReadiness.cxx | 96 ++ .../NamingService_WaitForServerReadiness.hxx | 36 + src/Registry/SALOME_Registry_Server.cxx | 8 +- .../SALOME_RessourcesCatalog_Handler.cxx | 4 + .../SALOME_RessourcesCatalog_Server.cxx | 9 +- src/SALOMEGUI/PyInterp_base.cxx | 1 + src/SALOMEGUI/QAD_PyInterp_mono.cxx | 2 + src/SALOMELocalTrace/LocalTraceBufferPool.cxx | 217 +++++ src/SALOMELocalTrace/LocalTraceBufferPool.hxx | 71 ++ src/SALOMELocalTrace/LocalTraceCollector.cxx | 278 ++++++ src/SALOMELocalTrace/LocalTraceCollector.hxx | 54 ++ .../LocalTrace_WaitForServerReadiness.cxx | 131 +++ .../LocalTrace_WaitForServerReadiness.hxx | 36 + src/SALOMELocalTrace/Makefile.in | 10 +- src/SALOMELocalTrace/utilities.h | 124 +++ src/SALOMELogger/Makefile.in | 50 -- src/SALOMELogger/SALOME_LoggerClient.cxx | 156 ---- src/Session/SALOME_Session_Server.cxx | 15 +- src/Session/Session_ServerThread.cxx | 71 +- src/Session/Session_ServerThread.hxx | 3 - src/Utils/Makefile.in | 1 - src/Utils/duplicate.cxx | 9 +- 32 files changed, 1653 insertions(+), 636 deletions(-) create mode 100644 src/NamingService/NamingService_WaitForServerReadiness.cxx create mode 100644 src/NamingService/NamingService_WaitForServerReadiness.hxx create mode 100644 src/SALOMELocalTrace/LocalTraceBufferPool.cxx create mode 100644 src/SALOMELocalTrace/LocalTraceBufferPool.hxx create mode 100644 src/SALOMELocalTrace/LocalTraceCollector.cxx create mode 100644 src/SALOMELocalTrace/LocalTraceCollector.hxx create mode 100644 src/SALOMELocalTrace/LocalTrace_WaitForServerReadiness.cxx create mode 100644 src/SALOMELocalTrace/LocalTrace_WaitForServerReadiness.hxx create mode 100644 src/SALOMELocalTrace/utilities.h delete mode 100644 src/SALOMELogger/Makefile.in delete mode 100644 src/SALOMELogger/SALOME_LoggerClient.cxx diff --git a/bin/runSalome.py b/bin/runSalome.py index 400866a1b..1274e9a45 100755 --- a/bin/runSalome.py +++ b/bin/runSalome.py @@ -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 _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 _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 _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() diff --git a/src/Container/SALOME_Container.cxx b/src/Container/SALOME_Container.cxx index a324089b7..41a526d0a 100644 --- a/src/Container/SALOME_Container.cxx +++ b/src/Container/SALOME_Container.cxx @@ -35,6 +35,7 @@ #include "SALOME_NamingService.hxx" #include "SALOME_Container_i.hxx" #include "utilities.h" +#include "LocalTraceCollector.hxx" #ifdef CHECKTIME #include @@ -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_::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_::Instance() ; - ASSERT(SINGLETON_::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 ; } diff --git a/src/DataTypeCatalog/SALOME_DataTypeCatalog_Handler.cxx b/src/DataTypeCatalog/SALOME_DataTypeCatalog_Handler.cxx index 47f8fb92d..26178c295 100644 --- a/src/DataTypeCatalog/SALOME_DataTypeCatalog_Handler.cxx +++ b/src/DataTypeCatalog/SALOME_DataTypeCatalog_Handler.cxx @@ -30,6 +30,10 @@ #include "utilities.h" +#include "SALOME_DataTypeCatalog_Handler.hxx" + +#include "utilities.h" + using namespace std; // contains all the data types defined in the catalog diff --git a/src/DataTypeCatalog/SALOME_DataTypeCatalog_Server.cxx b/src/DataTypeCatalog/SALOME_DataTypeCatalog_Server.cxx index a29401c51..988cd8961 100644 --- a/src/DataTypeCatalog/SALOME_DataTypeCatalog_Server.cxx +++ b/src/DataTypeCatalog/SALOME_DataTypeCatalog_Server.cxx @@ -30,16 +30,18 @@ #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; } diff --git a/src/Loader/InquireServersQThread.cxx b/src/Loader/InquireServersQThread.cxx index c5cf70377..d93260dc2 100644 --- a/src/Loader/InquireServersQThread.cxx +++ b/src/Loader/InquireServersQThread.cxx @@ -8,6 +8,7 @@ // $Header$ using namespace std; +#include "utilities.h" #include "InquireServersQThread.h" #include @@ -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++; } diff --git a/src/Loader/SALOME_Session_Loader.cxx b/src/Loader/SALOME_Session_Loader.cxx index 3aff04564..09cdad05e 100644 --- a/src/Loader/SALOME_Session_Loader.cxx +++ b/src/Loader/SALOME_Session_Loader.cxx @@ -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_::Instance() ; ASSERT(SINGLETON_::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 ; } diff --git a/src/MPIContainer/SALOME_MPIContainer.cxx b/src/MPIContainer/SALOME_MPIContainer.cxx index f11dbb26d..d6e19149e 100644 --- a/src/MPIContainer/SALOME_MPIContainer.cxx +++ b/src/MPIContainer/SALOME_MPIContainer.cxx @@ -28,10 +28,12 @@ using namespace std; #include #include "MPIContainer_i.hxx" #include "utilities.h" +#include "LocalTraceCollector.hxx" #include 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; } diff --git a/src/Makefile.in b/src/Makefile.in index 1eaa66af2..684d62305 100644 --- a/src/Makefile.in +++ b/src/Makefile.in @@ -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 \ diff --git a/src/ModuleCatalog/SALOME_ModuleCatalog_Server.cxx b/src/ModuleCatalog/SALOME_ModuleCatalog_Server.cxx index a15d54759..942c8f33d 100644 --- a/src/ModuleCatalog/SALOME_ModuleCatalog_Server.cxx +++ b/src/ModuleCatalog/SALOME_ModuleCatalog_Server.cxx @@ -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; } diff --git a/src/NamingService/Makefile.in b/src/NamingService/Makefile.in index 395e92922..2951501b1 100644 --- a/src/NamingService/Makefile.in +++ b/src/NamingService/Makefile.in @@ -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 index 000000000..b2ba19a51 --- /dev/null +++ b/src/NamingService/NamingService_WaitForServerReadiness.cxx @@ -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 +#include + +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 index 000000000..e65693117 --- /dev/null +++ b/src/NamingService/NamingService_WaitForServerReadiness.hxx @@ -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 +#include "SALOME_NamingService.hxx" + +void NamingService_WaitForServerReadiness(SALOME_NamingService* NS, + std::string serverName); + +#endif diff --git a/src/Registry/SALOME_Registry_Server.cxx b/src/Registry/SALOME_Registry_Server.cxx index 3e5a5b636..510366547 100644 --- a/src/Registry/SALOME_Registry_Server.cxx +++ b/src/Registry/SALOME_Registry_Server.cxx @@ -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_::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_::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 ; } diff --git a/src/RessourcesCatalog/SALOME_RessourcesCatalog_Handler.cxx b/src/RessourcesCatalog/SALOME_RessourcesCatalog_Handler.cxx index 565170301..d44450d9c 100755 --- a/src/RessourcesCatalog/SALOME_RessourcesCatalog_Handler.cxx +++ b/src/RessourcesCatalog/SALOME_RessourcesCatalog_Handler.cxx @@ -30,6 +30,10 @@ #include "utilities.h" +#include "SALOME_RessourcesCatalog_Handler.hxx" + +#include "utilities.h" + using namespace std; ListOfParserressources _ressources_list; diff --git a/src/RessourcesCatalog/SALOME_RessourcesCatalog_Server.cxx b/src/RessourcesCatalog/SALOME_RessourcesCatalog_Server.cxx index 4275a4924..f8018d340 100644 --- a/src/RessourcesCatalog/SALOME_RessourcesCatalog_Server.cxx +++ b/src/RessourcesCatalog/SALOME_RessourcesCatalog_Server.cxx @@ -30,19 +30,19 @@ #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; } diff --git a/src/SALOMEGUI/PyInterp_base.cxx b/src/SALOMEGUI/PyInterp_base.cxx index 08990e6e5..83ea5e040 100644 --- a/src/SALOMEGUI/PyInterp_base.cxx +++ b/src/SALOMEGUI/PyInterp_base.cxx @@ -10,6 +10,7 @@ // $Header$ + #include #include diff --git a/src/SALOMEGUI/QAD_PyInterp_mono.cxx b/src/SALOMEGUI/QAD_PyInterp_mono.cxx index 611b0e49b..695f64919 100644 --- a/src/SALOMEGUI/QAD_PyInterp_mono.cxx +++ b/src/SALOMEGUI/QAD_PyInterp_mono.cxx @@ -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 index 000000000..73046c6ec --- /dev/null +++ b/src/SALOMELocalTrace/LocalTraceBufferPool.cxx @@ -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 +#include + +#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 +#include + +#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 index 000000000..0cb334b40 --- /dev/null +++ b/src/SALOMELocalTrace/LocalTraceCollector.cxx @@ -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 +#include +#include +#include +#include + +using namespace std; + +#include "LocalTraceCollector.hxx" +#include "LocalTrace_WaitForServerReadiness.hxx" +//#include "SALOME_Log.hxx" +#include +#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="<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 index 000000000..90101efd3 --- /dev/null +++ b/src/SALOMELocalTrace/LocalTraceCollector.hxx @@ -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 +#include +#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 index 000000000..75a09525a --- /dev/null +++ b/src/SALOMELocalTrace/LocalTrace_WaitForServerReadiness.cxx @@ -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 +#include + +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 index 000000000..a5e1c9a89 --- /dev/null +++ b/src/SALOMELocalTrace/LocalTrace_WaitForServerReadiness.hxx @@ -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 +#include + +CORBA::Object_ptr LocalTrace_WaitForServerReadiness(CORBA::ORB_ptr theOrb, + std::string serverName); + +#endif diff --git a/src/SALOMELocalTrace/Makefile.in b/src/SALOMELocalTrace/Makefile.in index 6e3674a3e..5928c6409 100644 --- a/src/SALOMELocalTrace/Makefile.in +++ b/src/SALOMELocalTrace/Makefile.in @@ -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 index 000000000..94543b9f2 --- /dev/null +++ b/src/SALOMELocalTrace/utilities.h @@ -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 +#include +#include +#include + +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<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 < -#include - -using namespace std; - -#include "SALOME_Log.hxx" - -#include -#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----"<freeze(false); - seekp(0); - - if (CORBA::is_nil(m_pInterfaceLogger)) - cout << LogMsg << std::flush; - else - m_pInterfaceLogger-> putMessage (LogMsg) ; - } - diff --git a/src/Session/SALOME_Session_Server.cxx b/src/Session/SALOME_Session_Server.cxx index cd9060a3c..2a8522145 100644 --- a/src/Session/SALOME_Session_Server.cxx +++ b/src/Session/SALOME_Session_Server.cxx @@ -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_::Instance() ; + int orbArgc = 1; + CORBA::ORB_var &orb = init( orbArgc , argv ) ; + LocalTraceCollector *myThreadTrace = LocalTraceCollector::instance(orb); try { - SALOME_Event::GetSessionThread(); - - ORB_INIT &init = *SINGLETON_::Instance() ; - ASSERT(SINGLETON_::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 ; } diff --git a/src/Session/Session_ServerThread.cxx b/src/Session/Session_ServerThread.cxx index be3f1a4f2..886aef9b9 100644 --- a/src/Session/Session_ServerThread.cxx +++ b/src/Session/Session_ServerThread.cxx @@ -42,6 +42,7 @@ #include "Utils_SINGLETON.hxx" #include "Utils_SALOME_Exception.hxx" #include "OpUtil.hxx" +#include "NamingService_WaitForServerReadiness.hxx" #include "utilities.h" #include @@ -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; } diff --git a/src/Session/Session_ServerThread.hxx b/src/Session/Session_ServerThread.hxx index 73737cb45..b7dfc2c86 100644 --- a/src/Session/Session_ServerThread.hxx +++ b/src/Session/Session_ServerThread.hxx @@ -37,9 +37,6 @@ using namespace std; -void WaitForServerReadiness(string serverName); - - class Session_ServerThread { public: diff --git a/src/Utils/Makefile.in b/src/Utils/Makefile.in index b320657b1..f7f5d5a65 100644 --- a/src/Utils/Makefile.in +++ b/src/Utils/Makefile.in @@ -36,7 +36,6 @@ VPATH=.:@srcdir@:@top_srcdir@/idl # header files EXPORT_HEADERS= \ - utilities.h \ OpUtil.hxx \ Utils_Timer.hxx \ Utils_CorbaException.hxx \ diff --git a/src/Utils/duplicate.cxx b/src/Utils/duplicate.cxx index b1e449ce4..fa6cff737 100644 --- a/src/Utils/duplicate.cxx +++ b/src/Utils/duplicate.cxx @@ -31,11 +31,10 @@ * It is strongly (and only) used in the Registry environment * (RegistryService, RegistryConnexion, Identity, ...) */ -extern "C" -{ -#include -#include -} + +#include +#include + #include "utilities.h" using namespace std; -- 2.39.2