if WITHONLYLAUNCHER
SUBDIRS = src resources
else
- SUBDIRS = $(IDLDIR) salome_adm src doc bin resources
+ SUBDIRS = salome_adm $(IDLDIR) src doc bin resources
endif
-DIST_SUBDIRS= idl salome_adm src doc bin resources
+DIST_SUBDIRS= salome_adm idl src doc bin resources
DISTCLEANFILES = a.out
#
# These files are data, module or lib files
-dist_salomescript_DATA= \
- VERSION \
- orbmodule.py \
- salomeConsole.py \
- salome_session.py
+dist_salomescript_DATA = \
+ config_appli.xml \
+ salome.launch \
+ VERSION
# These files are executable scripts
-dist_salomescript_SCRIPTS=\
- envSalome.py \
- runIDLparser \
- runSalome.py \
- killSalome.py \
- killSalomeWithPort.py \
- runSalome \
- runSalome.csh \
- runNS.sh \
- createAppli.sh \
- appli_install.sh \
- appli_clean.sh \
- appli_gen.py \
- virtual_salome.py \
- config_appli.xml \
- launchConfigureParser.py \
- showNS.py \
- addToKillList.py \
- NSparam.py \
- setenv.py \
- launchSalome.py \
- nameserver.py \
- server.py \
- waitNS.sh \
- waitNS.py \
- waitContainers.py \
- shutdownSalome.py
+dist_salomescript_SCRIPTS = \
+ addToKillList.py \
+ appli_clean.sh \
+ appli_gen.py \
+ appli_install.sh \
+ createAppli.sh \
+ envSalome.py \
+ killSalome.py \
+ killSalomeWithPort.py \
+ launchConfigureParser.py \
+ launchSalome.py \
+ nameserver.py \
+ NSparam.py \
+ orbmodule.py \
+ runIDLparser \
+ runNS.py \
+ runNS.sh \
+ runSalome \
+ runSalome.csh \
+ runSalome.ksh \
+ runSalome.py \
+ salomeConsole.py \
+ salome_session.py \
+ salome_utilities.py \
+ server.py \
+ setenv.py \
+ showNS.py \
+ shutdownSalome.py \
+ virtual_salome.py \
+ waitContainers.py \
+ waitNS.py \
+ waitNS.sh
EXTRA_DIST = appliskel
DISTCLEANFILES = $(top_builddir)/bin/salome/Makefile.am
-clean-local:
- rm -rf $(top_builddir)/bin/salome/appliskel
- cd $(top_builddir)/bin/salome; \
- rm -f $(dist_salomescript_DATA) $(dist_salomescript_SCRIPTS)
-
# This is an ugly target to avoid exploring the appliskel subdirectory.
install-exec-local:
$(INSTALL) -d $(DESTDIR)$(salomescriptdir)
$(RM) -rf $(DESTDIR)$(salomescriptdir)/appliskel 1> /dev/null 2>&1
cp -r $(srcdir)/appliskel $(DESTDIR)$(salomescriptdir)
+ chmod a+x -R $(DESTDIR)$(salomescriptdir)/appliskel
find $(DESTDIR)$(salomescriptdir) -name CVS -prune -exec rm -rf {} \;
uninstall-local:
if test -d $(DESTDIR)$(salomescriptdir)/appliskel; then \
find $(DESTDIR)$(salomescriptdir)/appliskel -exec chmod +w {} ';' ; \
- rm -rf $(DESTDIR)$(salomescriptdir)/appliskel; \
- fi;
+ rm -rf $(DESTDIR)$(salomescriptdir)/appliskel; \
+ fi;
#
import sys,os
-import string
def getNSparams(info=""):
"""
elif info==port print host
else print 2 strings on stdout on one line: host port
"""
- my_port=""
- my_host=""
- if os.environ.has_key("OMNIORB_CONFIG"):
- file = open(os.environ["OMNIORB_CONFIG"], "r")
- s = file.readline()
- while len(s):
- l = string.split(s, ":")
- if string.split(l[0], " ")[0] == "ORBInitRef" or \
- string.split(l[0], " ")[0] == "InitRef" :
- my_port = l[len(l)-1]
- if my_port[-1] == '\n':
- my_port = my_port[:-1]
- pass
- my_host = l[len(l)-2]
- break;
- pass
- s = file.readline()
- pass
- pass
+ from salome_utilities import getORBcfgInfo
+ my_version, my_host, my_port = getORBcfgInfo()
if info=='host':
# keep print, stdout used in shell
print my_host
getNSparams('port')
pass
else:
- getNSparams('')
+ getNSparams()
pass
pass
else:
- getNSparams('')
+ getNSparams()
pass
+ pass
########## adds to the kill list of SALOME one more process ##########
def findFileDict():
- if os.environ.has_key('NSPORT'):
- my_port = os.environ['NSPORT']
- pass
- else:
- my_port = 2809
- try:
- file = open(os.environ["OMNIORB_CONFIG"], "r")
- s = file.read()
- while len(s):
- l = string.split(s, ":")
- if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
- my_port = int(l[len(l)-1])
- pass
- s = file.read()
- pass
- pass
- except:
- pass
- pass
- if verbose(): print "myport = ", my_port
- return my_port
+ """
+ Detect current SALOME session's port number.
+ Returns port number.
+ """
+ from salome_utilities import getPortNumber
+ port = getPortNumber()
+ if verbose(): print "myport = ", port
+ return port
-def addToKillList(command_pid, command):
- my_port = findFileDict()
+def addToKillList(command_pid, command, port=None):
+ """
+ Add the process to the SALOME processes dictionary file.
+ Parameters:
+ - command_pid : command PID
+ - command : command (string or list of strings)
+ - [port] : SALOME port number; if this parameter is None (default),
+ it is detected automatically
+ """
+ # retrieve current processes dictionary
from killSalomeWithPort import getPiDict
- filedict=getPiDict(my_port)
+ if port is None: port=findFileDict()
+ filedict=getPiDict(port)
try:
fpid=open(filedict, 'r')
process_ids=pickle.load(fpid)
fpid.close()
except:
- process_ids=[{}]
+ process_ids=[]
pass
-
- already_in=0
+ # check if PID is already in dictionary
+ already_in=False
for process_id in process_ids:
- if verbose(): print process_id
for pid, cmd in process_id.items():
- #print "see process %s : %s"% (pid, cmd[0])
- if pid == command_pid:
- already_in=1
- pass
+ if int(pid) == int(command_pid):
+ already_in=True
+ break
pass
+ if already_in: break
pass
-
- command=(command.split(" "))[0]
- if already_in == 0:
+ # add process to the dictionary
+ if not already_in:
+ import types
+ if type(command) == types.ListType: command=" ".join([str(c) for c in command])
+ command=command.split()[0]
try:
- process_ids.append({command_pid: [command]})
- fpid=open(filedict,'w')
+ if verbose(): print "addToKillList: %s : %s" % ( str(command_pid), command )
+ process_ids.append({int(command_pid): [command]})
+ dir = os.path.dirname(filedict)
+ if not os.path.exists(dir): os.makedirs(dir, 0777)
+ fpid = open(filedict,'w')
pickle.dump(process_ids, fpid)
fpid.close()
except:
- print "addToKillList: can not add command %s to the kill list"% filedict
+ if verbose(): print "addToKillList: can not add command %s : %s to the kill list" % ( str(command_pid), command )
pass
pass
pass
-def killList():
- my_port = findFileDict()
+def killList(port=None):
+ """
+ Kill all the processes listed in the SALOME processes dictionary file.
+ - [port] : SALOME port number; if this parameter is None (default),
+ it is detected automatically
+ """
+ # retrieve processes dictionary
from killSalomeWithPort import getPiDict
- filedict=getPiDict(my_port)
+ if port is None: port=findFileDict()
+ # new-style dot-prefixed pidict file
+ filedict=getPiDict(port, hidden=True)
+ # provide compatibility with old-style pidict file (not dot-prefixed)
+ if not os.path.exists(filedict): filedict = getPiDict(port, hidden=False)
try:
fpid=open(filedict, 'r')
process_ids=pickle.load(fpid)
fpid.close()
except:
- process_ids=[{}]
+ process_ids=[]
pass
-
+ # kill processes
for process_id in process_ids:
- print process_id
+ #print process_id
for pid, cmd in process_id.items():
print "stop process %s : %s"% (pid, cmd[0])
try:
pass
pass
pass
+ # remove processes dictionary file
os.remove(filedict)
pass
-
-
if __name__ == "__main__":
if verbose(): print sys.argv
addToKillList(sys.argv[1], sys.argv[2])
+ pass
#args, modules_list, modules_root_dir = setenv.get_config()
#runSalome.set_env(args, modules_list, modules_root_dir)
-setenv.main();
+setenv.main(True);
os.execvp(argv[0],argv)
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import os, string, sys, re
+import os, sys, re, signal
from killSalomeWithPort import killMyPort, getPiDict
def killAllPorts():
+ """
+ Kill all SALOME sessions belonging to the user.
+ """
user = os.getenv('USER')
- filedict = "^%s$"%(getPiDict('(\d*)',full=False))
- fnamere = re.compile(filedict)
- for file in os.listdir(os.getenv("HOME")):
- mo = re.match(fnamere,file)
- if mo and len(mo.groups()):
- killMyPort(mo.groups()[0])
+ # new-style dot-prefixed pidict file
+ fpidict = getPiDict('(\d*)',hidden=True)
+ dirpidict = os.path.dirname(fpidict)
+ fpidict = os.path.basename(fpidict)
+ fnamere = re.compile("^%s$" % fpidict)
+ try:
+ for f in os.listdir(dirpidict):
+ mo = fnamere.match(f)
+ try:
+ killMyPort(mo.group(1))
+ except:
+ pass
+ pass
pass
-
- if not sys.platform == 'win32':
- cmd = "pid=`ps -fea | grep '"+os.getenv('USER')+"' | grep 'ghs3d' | grep 'f /tmp/GHS3D_' | grep -v 'grep' | awk '{print $2}'` ; echo $pid > /tmp/logs/"+os.getenv('USER')+"/_"+"Pid_ghs3d.log"
- a = os.system(cmd)
- try:
- fpidomniNames=open('/tmp/logs/'+os.getenv('USER')+"/_"+"Pid_ghs3d.log")
- prc = fpidomniNames.read()
- fpidomniNames.close()
- if prc != None :
- for field in prc.split(" ") :
- field = field.strip()
- if field != None and len(field) != 0:
- os.system('kill -9 '+field)
- except:
+ except:
+ pass
+ # provide compatibility with old-style pidict file (not dot-prefixed)
+ fpidict = getPiDict('(\d*)',hidden=False)
+ dirpidict = os.path.dirname(fpidict)
+ fpidict = os.path.basename(fpidict)
+ fnamere = re.compile("^%s$" % fpidict)
+ try:
+ for f in os.listdir(dirpidict):
+ mo = fnamere.match(f)
+ try:
+ killMyPort(mo.group(1))
+ except:
+ pass
+ pass
+ pass
+ except:
+ pass
+ # kill other processes
+ if sys.platform != 'win32':
+ import commands
+ cmd = "ps -fea | grep '%s' | grep 'ghs3d' | grep 'f /tmp/GHS3D_' | grep -v 'grep' | awk '{print $2}'" % user
+ prc = commands.getoutput(cmd)
+ for field in prc.split():
+ try:
+ os.kill(int(field), signal.SIGKILL)
+ except:
+ pass
pass
pass
+ pass
if __name__ == "__main__":
killAllPorts()
+ pass
import os, sys, pickle, signal, commands
from launchConfigureParser import verbose
-def getPiDict(port,appname='salome',full=True):
- from Utils_Identity import getShortHostName
-
- # get hostname by special function in all cases to
- # have always same result in lower case at win32
- host = getShortHostName()
- if not host:
- host = os.getenv("HOSTNAME")
- if not host:
- host = os.getenv("HOST")
-
- filedict = []
- filedict.append( os.getenv('USER') ) # user name
- filedict.append( host ) # host name
- filedict.append( str(port) ) # port number
- filedict.append( appname.upper() ) # application name
- filedict.append( 'pidict' ) # constant part
+def getPiDict(port,appname='salome',full=True,hidden=True):
+ """
+ Get file with list of SALOME processes.
+ This file is located in the user's home directory
+ and named .<user>_<host>_<port>_SALOME_pidict
+ where
+ <user> is user name
+ <host> is host name
+ <port> is port number
- filedict = '_'.join(filedict)
+ Parameters:
+ - port : port number
+ - appname : application name (default is 'SALOME')
+ - full : if True, full path to the file is returned, otherwise only file name is returned
+ - hidden : if True, file name is prefixed with . (dot) symbol; this internal parameter is used
+ to support compatibility with older versions of SALOME
+ """
+ from salome_utilities import generateFileName, getTmpDir
+ dir = ""
if full:
- filedict = os.getenv("HOME") + '/' + filedict
- return filedict
+ # full path to the pidict file is requested
+ if hidden:
+ # new-style dot-prefixed pidict files
+ # are in the system-dependant temporary diretory
+ dir = getTmpDir()
+ else:
+ # old-style non-dot-prefixed pidict files
+ # are in the user's home directory
+ dir = os.getenv("HOME")
+ pass
+ pass
+ return generateFileName(dir,
+ suffix="pidict",
+ hidden=hidden,
+ with_username=True,
+ with_hostname=True,
+ with_port=port,
+ with_app=appname.upper())
def appliCleanOmniOrbConfig(port):
"""
- remove omniorb config files related to the port in SALOME application:
+ Remove omniorb config files related to the port in SALOME application:
- ${HOME}/${APPLI}/.omniORB_${HOSTNAME}_${NSPORT}.cfg
- ${HOME}/${APPLI}/.omniORB_last.cfg
the last is removed only if the link points to the first file.
"""
- from Utils_Identity import getShortHostName
- appli=os.environ.get("APPLI")
+ from salome_utilities import generateFileName
+ home = os.getenv("HOME")
+ appli = os.getenv("APPLI")
if appli is None:
#Run outside application context
pass
else:
- home = os.environ['HOME']
- home='%s/%s'%(home,appli)
- hostname=getShortHostName()
- omniorb_config = '%s/.omniORB_%s_%s.cfg'%(home,hostname, str(port))
- last_running_config = '%s/.omniORB_last.cfg'%(home)
+ dir = os.path.join(home, appli)
+ omniorb_config = generateFileName(dir, prefix="omniORB",
+ extension="cfg",
+ hidden=True,
+ with_hostname=True,
+ with_port=port)
+ last_running_config = generateFileName(dir, prefix="omniORB",
+ suffix="last",
+ extension="cfg",
+ hidden=True)
if os.access(last_running_config,os.F_OK):
pointedPath = os.readlink(last_running_config)
if pointedPath[0] != '/':
os.remove(omniorb_config)
pass
pass
+ pass
########## kills all salome processes with the given port ##########
def killMyPort(port):
- filedict=getPiDict(port)
- found = 0
+ """
+ Kill SALOME session running on the specified port.
+ Parameters:
+ - port - port number
+ """
+ # new-style dot-prefixed pidict file
+ filedict = getPiDict(port, hidden=True)
+ # provide compatibility with old-style pidict file (not dot-prefixed)
+ if not os.path.exists(filedict): filedict = getPiDict(port, hidden=False)
+ #
try:
- fpid=open(filedict, 'r')
- found = 1
- except:
- print "file %s giving SALOME process id is not readable"% filedict
- pass
-
- if found:
+ fpid = open(filedict, 'r')
+ #
+ from salome_utilities import generateFileName
+ fpidomniNames = generateFileName(os.path.join('/tmp/logs', os.getenv('USER')),
+ prefix="",
+ suffix="Pid_omniNames",
+ extension="log",
+ with_port=port)
if not sys.platform == 'win32':
- cmd = 'pid=`ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'"` ; echo $pid > /tmp/logs/'+os.getenv('USER')+"/_"+port+'_Pid_omniNames.log'
+ cmd = 'pid=`ps -eo pid,command | egrep "[0-9] omniNames -start %s"` ; echo $pid > %s' % ( str(port), fpidomniNames )
a = os.system(cmd)
+ pass
try:
- fpidomniNames=open('/tmp/logs/'+os.getenv('USER')+"/_"+port+'_Pid_omniNames.log')
- prc = fpidomniNames.read()
- fpidomniNames.close()
- if prc != None :
- for field in prc.split(" ") :
- if field == "omniNames" :
- if pidfield != "egrep" :
- if sys.platform == "win32":
- import win32pm
- print 'stop process '+pidfield+' : omniNames'
- win32pm.killpid(int(pidfield),0)
- else:
- if verbose(): print 'stop process '+pidfield+' : omniNames'
- os.system('kill -9 '+pidfield)
- pidfield = field
+ fpidomniNamesFile = open(fpidomniNames)
+ lines = fpidomniNamesFile.readlines()
+ fpidomniNamesFile.close()
+ os.remove(fpidomniNames)
+ for l in lines:
+ try:
+ pidfield = l.split()[0] # pid should be at the first position
+ if sys.platform == "win32":
+ import win32pm
+ if verbose(): print 'stop process '+pidfield+' : omniNames'
+ win32pm.killpid(int(pidfield),0)
+ else:
+ if verbose(): print 'stop process '+pidfield+' : omniNames'
+ os.kill(int(pidfield),signal.SIGKILL)
+ pass
+ pass
+ except:
+ pass
+ pass
+ pass
except:
pass
-
+ #
try:
process_ids=pickle.load(fpid)
fpid.close()
for process_id in process_ids:
-
for pid, cmd in process_id.items():
if verbose(): print "stop process %s : %s"% (pid, cmd[0])
try:
if sys.platform == "win32":
- import win32pm
- win32pm.killpid(int(pid),0)
+ import win32pm
+ win32pm.killpid(int(pid),0)
else:
- os.kill(int(pid),signal.SIGKILL)
+ os.kill(int(pid),signal.SIGKILL)
+ pass
+ pass
except:
if verbose(): print " ------------------ process %s : %s not found"% (pid, cmd[0])
pass
- pass
+ pass # for pid, cmd ...
+ pass # for process_id ...
+ pass # try...
except:
pass
-
+ #
os.remove(filedict)
cmd='ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'" | sed -e "s%[^0-9]*\([0-9]*\) .*%\\1%g"'
pid = commands.getoutput(cmd)
a = ""
- while pid != "" and len(a.split(" ")) < 2:
- a = commands.getoutput("pid=`ps -eo pid,command | egrep \"[0-9] omniNames -start "+str(port)+"\" | sed -e \"s%[^0-9]*\([0-9]*\) .*%\\1%g\"`; kill -9 $pid")
- pid = commands.getoutput("ps -eo pid,command | egrep \"[0-9] omniNames -start "+str(port)+"\" | sed -e \"s%[^0-9]*\([0-9]*\) .*%\\1%g\"")
- print pid
-
+ while pid and len(a.split()) < 2:
+ a = commands.getoutput("kill -9 " + pid)
+ pid = commands.getoutput(cmd)
+ #print pid
+ pass
pass
-
+ except:
+ print "Cannot find or open SALOME PIDs file for port", port
+ pass
+ #
appliCleanOmniOrbConfig(port)
pass
-
if __name__ == "__main__":
for port in sys.argv[1:]:
killMyPort(port)
+ pass
+ pass
dirs += re.split(';', os.getenv(config_var))
else:
dirs += re.split('[;|:]', os.getenv(config_var))
-
+
+ gui_available = True
if os.getenv("GUI_ROOT_DIR") and os.path.isdir( os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui" ):
dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
+ pass
+ else:
+ gui_available = False
+ if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel" ):
+ dirs += [os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel"]
+ pass
os.environ[config_var] = separator.join(dirs)
dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
args[gui_nam] = cmd_opts.gui
if cmd_opts.batch is not None:
args[batch_nam] = True
+
+ if not gui_available:
+ args[gui_nam] = False
+
if args[gui_nam]:
args["session_gui"] = True
if cmd_opts.desktop is not None:
#import commands
from server import *
from Utils_Identity import getShortHostName
+from launchConfigureParser import verbose
# -----------------------------------------------------------------------------
#os.system("touch " + upath + "/dummy")
for fname in os.listdir(upath):
try:
- os.remove(upath + "/" + fname)
+ if not fname.startswith("."): os.remove(upath + "/" + fname)
except:
pass
#os.system("rm -f " + upath + "/omninames* " + upath + "/dummy " + upath + "/*.log")
- print "Name Service... ",
+ if verbose(): print "Name Service... ",
#hname=os.environ["HOST"] #commands.getoutput("hostname")
if sys.platform == "win32":
hname=getShortHostName();
f=open(os.environ["OMNIORB_CONFIG"])
ss=re.findall("NameService=corbaname::" + hname + ":\d+", f.read())
- print "ss = ", ss,
+ if verbose(): print "ss = ", ss,
f.close()
sl=ss[0]
ll = sl.split(':')
#print "port=", aPort
if sys.platform == "win32":
#print "start omniNames -start " + aPort + " -logdir " + upath
- self.CMD=['omniNames -start ' , aPort , ' -logdir ' , '\"' + upath + '\"']
+ self.CMD=['omniNames -start ' , aPort , ' -logdir ' , '\"' + upath + '\"', ' -errlog', upath+'/omniNameErrors.log']
#os.system("start omniNames -start " + aPort + " -logdir " + upath)
else:
#self.CMD=['omniNames -start ' , aPort , ' -logdir ' , upath , ' &']
- self.CMD=['omniNames','-start' , aPort, '-logdir' , upath ]
+ self.CMD=['omniNames','-start' , aPort, '-logdir' , upath, '-errlog', upath+'/omniNameErrors.log']
#os.system("omniNames -start " + aPort + " -logdir " + upath + " &")
- print "... ok"
- print "to list contexts and objects bound into the context with the specified name : showNS "
+ if verbose(): print "... ok"
+ if verbose(): print "to list contexts and objects bound into the context with the specified name : showNS "
def initArgs(self):
import string
from nameserver import *
from omniORB import CORBA
+from launchConfigureParser import verbose
# Import the stubs for the Naming service
import CosNaming
return
except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
self.rootContext = None
- print "Launch Naming Service++",
+ if verbose(): print "Launch Naming Service++",
# On lance le Naming Server (doit etre dans le PATH)
NamingServer(args).run()
#os.system("touch " + upath + "/dummy")
for fname in os.listdir(upath):
try:
- os.remove(upath + "/" + fname)
+ if not fname.startswith("."): os.remove(upath + "/" + fname)
except:
pass
#os.system("rm -f " + upath + "/omninames* " + upath + "/dummy " + upath + "/*.log")
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import sys, os, string, glob, time, pickle
+import sys, os, string, glob, time, pickle, re
import orbmodule
import setenv
from server import *
def __init__(self,args):
self.args=args
self.initArgs()
- if sys.platform == "win32":
- self.CMD=['SALOME_Logger_Server', os.environ["HOME"] + "/logger.log"];
- else:
- self.CMD=['SALOME_Logger_Server', 'logger.log']
+ from salome_utilities import generateFileName
+ if sys.platform == "win32": dirpath = os.environ["HOME"]
+ else: dirpath = "/tmp"
+ logfile = generateFileName( dirpath,
+ prefix="logger",
+ extension="log",
+ with_username=True,
+ with_hostname=True,
+ with_port=True)
+ print "==========================================================="
+ print "Logger server: put log to the file:"
+ print logfile
+ print "==========================================================="
+ self.CMD=['SALOME_Logger_Server', logfile]
+ pass
+ pass # end of LoggerServer class
# ---
# Notify Server launch
#
- if verbose(): print "Notify Server to launch"
-
if sys.platform != "win32":
- print "Notify Server to launch"
+ if verbose(): print "Notify Server to launch"
myServer=NotifyServer(args,modules_root_dir)
myServer.run()
#print process_id
+ from addToKillList import addToKillList
from killSalomeWithPort import getPiDict
- filedict = getPiDict(args['port'])
- process_ids = []
- try:
- fpid=open(filedict, 'r')
- process_ids=pickle.load(fpid)
- fpid.close()
- except:
+ filedict = getPiDict(args['port'])
+ for pid, cmd in process_id.items():
+ addToKillList(pid, cmd, args['port'])
pass
-
- fpid=open(filedict, 'w')
- process_ids.append(process_id)
- pickle.dump(process_ids,fpid)
- fpid.close()
-
+
if verbose(): print """
Saving of the dictionary of Salome processes in %s
To kill SALOME processes from a console (kill all sessions from all ports):
def searchFreePort(args, save_config=1):
print "Searching for a free port for naming service:",
+ #
+ if sys.platform == "win32":
+ tmp_file = os.getenv('TEMP');
+ else:
+ tmp_file = '/tmp'
+ tmp_file = os.path.join(tmp_file, '.netstat_%s'%os.getpid())
+ #
+ ###status = os.system("netstat -ltn | grep -E :%s > /dev/null 2>&1"%(NSPORT))
+ os.system( "netstat -a -n > %s" % tmp_file );
+ f = open( tmp_file, 'r' );
+ ports = f.readlines();
+ f.close();
+ os.remove( tmp_file );
+ #
+ def portIsUsed(port, data):
+ regObj = re.compile( "tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
+ for item in data:
+ try:
+ p = int(regObj.match(item).group(1))
+ if p == port: return True
+ pass
+ except:
+ pass
+ pass
+ return False
+ #
NSPORT=2810
- limit=NSPORT
- limit=limit+10
+ limit=NSPORT+100
+ #
while 1:
- import os
- import re
- from os import getpid
- from os import system
-
- if sys.platform == "win32":
- tmp_file = os.getenv('TEMP');
- else:
- tmp_file = '/tmp/'
- tmp_file += 'hostname_%s'%(getpid())
-
-# status = os.system("netstat -ltn | grep -E :%s > /dev/null 2>&1"%(NSPORT))
-
- system( "netstat -a -n > %s" % tmp_file );
-
- f = open( tmp_file, 'r' );
- lines = f.readlines();
- f.close();
-
- pattern = "tcp.*:([0-9]+).*:.*listen";
- regObj = re.compile( pattern, re.IGNORECASE );
-
- status = 1;
- for item in lines:
- m = regObj.search( item )
- if m:
- try:
- p = int( m.group(1) )
- if p == NSPORT:
- status = 0;
- break;
- except:
- pass
- pass
-
- if status == 1:
+ if not portIsUsed(NSPORT, ports):
print "%s - OK"%(NSPORT)
#
- system('hostname > %s'%(tmp_file))
- f = open(tmp_file)
- myhost = f.read()
- myhost = myhost[:-1]
- f.close()
-
- os.remove( tmp_file );
-
+ from salome_utilities import generateFileName, getHostName
+ hostname = getHostName()
#
- home = os.environ['HOME']
- appli=os.environ.get("APPLI")
- if appli is not None:
- home='%s/%s'%(home,appli)
- pass
+ home = os.getenv("HOME")
+ appli = os.getenv("APPLI")
+ if appli is not None: home = os.path.join(home, appli)
#
- os.environ['OMNIORB_CONFIG'] = '%s/.omniORB_%s_%s.cfg'%(home, myhost, NSPORT)
- initref = "NameService=corbaname::%s:%s"%(myhost, NSPORT)
- os.environ['NSPORT'] = "%s"%(NSPORT)
- os.environ['NSHOST'] = "%s"%(myhost)
- f = open(os.environ['OMNIORB_CONFIG'], "w")
+ omniorb_config = generateFileName(home, prefix="omniORB",
+ extension="cfg",
+ hidden=True,
+ with_hostname=True,
+ with_port=NSPORT)
+ orbdata = []
+ initref = "NameService=corbaname::%s:%s"%(hostname, NSPORT)
import CORBA
if CORBA.ORB_ID == "omniORB4":
- initref += "\ngiopMaxMsgSize = 2097152000 # 2 GBytes";
- initref += "\ntraceLevel = 0 # critical errors only";
- f.write("InitRef = %s\n"%(initref))
+ orbdata.append("InitRef = %s"%(initref))
+ orbdata.append("giopMaxMsgSize = 2097152000 # 2 GBytes")
+ orbdata.append("traceLevel = 0 # critical errors only")
else:
- initref += "\nORBgiopMaxMsgSize = 2097152000 # 2 GBytes";
- initref += "\nORBtraceLevel = 0 # critical errors only";
- f.write("ORBInitRef %s\n"%(initref))
+ orbdata.append("ORBInitRef %s"%(initref))
+ orbdata.append("ORBgiopMaxMsgSize = 2097152000 # 2 GBytes")
+ orbdata.append("ORBtraceLevel = 0 # critical errors only")
pass
+ orbdata.append("")
+ f = open(omniorb_config, "w")
+ f.write("\n".join(orbdata))
f.close()
+ #
+ os.environ['OMNIORB_CONFIG'] = omniorb_config
+ os.environ['NSPORT'] = "%s"%(NSPORT)
+ os.environ['NSHOST'] = "%s"%(hostname)
args['port'] = os.environ['NSPORT']
#
if save_config:
- from os import system
- if sys.platform == "win32":
- import shutil
- shutil.copyfile( os.environ['OMNIORB_CONFIG'], "%s/.omniORB_last.cfg"%( home ) )
- else:
- system('ln -s -f %s %s/.omniORB_last.cfg'%(os.environ['OMNIORB_CONFIG'], home))
- pass
+ last_running_config = generateFileName(home, prefix="omniORB",
+ suffix="last",
+ extension="cfg",
+ hidden=True)
+ try:
+ if sys.platform == "win32":
+ import shutil
+ shutil.copyfile(omniorb_config, last_running_config)
+ else:
+ try:
+ os.remove(last_running_config)
+ except OSError:
+ pass
+ os.symlink(omniorb_config, last_running_config)
+ pass
+ pass
+ except:
+ pass
break
print "%s"%(NSPORT),
if NSPORT == limit:
def main():
"""Salome launch as a main application"""
import sys
- print "runSalome running on ",os.getenv('HOSTNAME')
+ from salome_utilities import getHostName
+ print "runSalome running on %s" % getHostName()
args, modules_list, modules_root_dir = setenv.get_config()
kill_salome(args)
save_config = True
if args.has_key('save_config'):
save_config = args['save_config']
searchFreePort(args, save_config)
- setenv.main()
+ #setenv.main()
+ setenv.set_env(args, modules_list, modules_root_dir)
clt = useSalome(args, modules_list, modules_root_dir)
return clt,args
socket.gethostname() gives short or complete Hostname, depending on
defined aliases.
"""
- return string.split(socket.gethostname(),'.')[0]
+ from salome_utilities import getShortHostName
+ return getShortHostName()
def searchFreePort():
+ """
+ Search free port for SALOME session.
+ Returns first found free port number.
+ """
print "Searching a free port for naming service:",
- NSPORT=2810
- limit=NSPORT
- limit=limit+100
+ from salome_utilities import generateFileName, getHostName
+ hostname = getHostName()
+ NSPORT = 2810
+ limit = NSPORT+100
while 1:
print "%s "%(NSPORT),
status = os.system("netstat -ltn | grep -E :%s"%(NSPORT))
if status:
- home = os.environ['HOME']
- appli=os.environ.get("APPLI")
- if appli is None:
- #Run outside application context
- home=home
- else:
- home='%s/%s'%(home,appli)
- hostname=getShortHostName()
- omniorb_config = '%s/.omniORB_%s_%s.cfg'%(home,hostname, NSPORT)
- os.environ['OMNIORB_CONFIG'] = omniorb_config
+ home = os.getenv("HOME")
+ appli = os.getenv("APPLI")
+ if appli is not None: home = os.path.join(home, appli)
+ omniorb_config = generateFileName(home, prefix="omniORB",
+ extension="cfg",
+ hidden=True,
+ with_hostname=True,
+ with_port=NSPORT)
f = open(omniorb_config, "w")
f.write("ORBInitRef NameService=corbaname::%s:%s\n"%(hostname, NSPORT))
f.close()
- last_running_config = '%s/.omniORB_last.cfg'%(home, hostname)
+ os.environ['OMNIORB_CONFIG'] = omniorb_config
+ last_running_config = generateFileName(home, prefix="omniORB",
+ suffix="last",
+ extension="cfg",
+ hidden=True)
os.environ['LAST_RUNNING_CONFIG'] = last_running_config
if os.access(last_running_config,os.F_OK):
os.unlink(last_running_config)
pass
os.symlink(omniorb_config,last_running_config)
- # LAST_RUNNING_CONFIG=${HOME}/${APPLI}/.omniORB_${myhost}_last.cfg
print "- Ok"
break
if NSPORT == limit:
msg = ""
- msg += "I Can't find a free port to launch omniNames\n"
- msg += "I suggest you to kill the running servers and try again.\n"
+ msg += "Can not find a free port to launch omniNames\n"
+ msg += "Kill the running servers and try again.\n"
raise msg
- NSPORT=NSPORT+1
+ NSPORT = NSPORT+1
pass
- os.environ['NSHOST']=hostname
- os.environ['NSPORT']=str(NSPORT)
+ os.environ['NSHOST'] = hostname
+ os.environ['NSPORT'] = str(NSPORT)
return NSPORT
--- /dev/null
+# Copyright (C) 2005 OPEN CASCADE, CEA, EDF R&D, LEG
+# PRINCIPIA R&D, EADS CCR, Lip6, BV, CEDRAT
+# 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.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+# ---
+#
+# File : salome_utilities.py
+# Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
+#
+# ---
+
+"""
+Set of utility functions used by SALOME python scripts.
+"""
+
+#
+# Exported functions
+#
+__all__ = [
+ 'getORBcfgInfo',
+ 'getHostFromORBcfg',
+ 'getPortFromORBcfg',
+ 'getUserName',
+ 'getHostName',
+ 'getShortHostName',
+ 'getAppName',
+ 'getPortNumber',
+ 'getTmpDir',
+ 'generateFileName',
+ ]
+
+# ---
+
+def _try_bool( arg ):
+ """
+ Check if specified parameter represents boolean value and returns its value.
+ String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
+ are supported.
+ If <arg> does not represent a boolean, an exception is raised.
+ """
+ import types
+ if type( arg ) == types.BooleanType :
+ return arg
+ elif type( arg ) == types.StringType :
+ v = str( arg ).lower()
+ if v in [ "yes", "y", "true" ]: return True
+ elif v in [ "no", "n", "false" ]: return False
+ pass
+ raise Exception("Not boolean value")
+
+# ---
+
+def getORBcfgInfo():
+ """
+ Get omniORB current configuration.
+ Returns a list of three values: [ orb_version, host_name, port_number ].
+
+ The information is retrieved from the omniORB configuration file defined
+ by the OMNIORB_CONFIG environment variable.
+ If omniORB configuration file can not be accessed, a list of three empty
+ strings is returned.
+ """
+ import os, re
+ ret = [ "", "", "" ]
+ try:
+ f = open( os.getenv( "OMNIORB_CONFIG" ) )
+ lines = f.readlines()
+ f.close()
+ regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )
+ for l in lines:
+ try:
+ m = regvar.match( l )
+ if m:
+ if m.group(1) is None:
+ ret[0] = "4"
+ else:
+ ret[0] = "3"
+ pass
+ ret[1] = m.group(2)
+ ret[2] = m.group(3)
+ break
+ pass
+ except:
+ pass
+ pass
+ pass
+ except:
+ pass
+ return ret
+
+# ---
+
+def getHostFromORBcfg():
+ """
+ Get current omniORB host.
+ """
+ return getORBcfgInfo()[1]
+# ---
+
+def getPortFromORBcfg():
+ """
+ Get current omniORB port.
+ """
+ return getORBcfgInfo()[2]
+
+# ---
+
+def getUserName():
+ """
+ Get user name:
+ 1. try USER environment variable
+ 2. if fails, return 'unknown' as default user name
+ """
+ import os
+ return os.getenv( "USER", "unknown" ) # 'unknown' is default user name
+
+# ---
+
+def getHostName():
+ """
+ Get host name:
+ 1. try socket python module gethostname() function
+ 2. if fails, try HOSTNAME environment variable
+ 3. if fails, try HOST environment variable
+ 4. if fails, return 'unknown' as default host name
+ """
+ import os
+ try:
+ import socket
+ host = socket.gethostname()
+ except:
+ host = None
+ pass
+ if not host: host = os.getenv("HOSTNAME")
+ if not host: host = os.getenv("HOST")
+ if not host: host = "unknown" # 'unknown' is default host name
+ return host
+
+# ---
+
+def getShortHostName():
+ """
+ Get short host name:
+ 1. try socket python module gethostname() function
+ 2. if fails, try HOSTNAME environment variable
+ 3. if fails, try HOST environment variable
+ 4. if fails, return 'unknown' as default host name
+ """
+ try:
+ return getHostName().split('.')[0]
+ except:
+ pass
+ return "unknown" # 'unknown' is default host name
+
+# ---
+
+def getAppName():
+ """
+ Get application name:
+ 1. try APPNAME environment variable
+ 2. if fails, return 'SALOME' as default application name
+ """
+ import os
+ return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
+
+# ---
+
+def getPortNumber():
+ """
+ Get current naming server port number:
+ 1. try NSPORT environment variable
+ 1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
+ 2. if fails, return 2809 as default port number
+ """
+ import os
+ try:
+ return int( os.getenv( "NSPORT" ) )
+ except:
+ pass
+ port = getPortFromORBcfg()
+ if port is not None: return port
+ return 2809 # '2809' is default port number
+
+# ---
+
+def getTmpDir():
+ """
+ Get directory to be used for the temporary files.
+ """
+ import os, sys
+ if sys.platform == "win32":
+ # for Windows: temporarily using home directory for tmp files;
+ # to be replaced with TEMP environment variable later...
+ dir = os.getenv("HOME")
+ else:
+ # for Linux: use /tmp/logs/{user} folder
+ dir = os.path.join( '/tmp', 'logs', getUserName() )
+ pass
+ return dir
+
+# ---
+
+def generateFileName( dir, prefix = None, suffix = None, extension = None,
+ unique = False, separator = "_", hidden = False, **kwargs ):
+ """
+ Generate file name by sepecified parameters. If necessary, file name
+ can be generated to be unique.
+
+ Parameters:
+ - dir : directory path
+ - prefix : file prefix (not added by default)
+ - suffix : file suffix (not added by default)
+ - extension : file extension (not added by default)
+ - unique : if this parameter is True, the unique file name is generated:
+ in this case, if the file with the generated name already exists
+ in the <dir> directory, an integer suffix is added to the end of the
+ file name. This parameter is False by default.
+ - separator : separator of the words ('_' by default)
+ - hidden : if this parameter is True, the file name is prepended by . (dot)
+ symbol. This parameter is False by default.
+
+ Other keyword parameters are:
+ - with_username : 'add user name' flag/option:
+ * boolean value can be passed to determine user name automatically
+ * string value to be used as user name
+ - with_hostname : 'add host name' flag/option:
+ * boolean value can be passed to determine host name automatically
+ * string value to be used as host name
+ - with_port : 'add port number' flag/option:
+ * boolean value can be passed to determine port number automatically
+ * string value to be used as port number
+ - with_app : 'add application name' flag/option:
+ * boolean value can be passed to determine application name automatically
+ * string value to be used as application name
+ All <with_...> parameters are optional.
+ """
+ supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
+ from launchConfigureParser import verbose
+ filename = []
+ # separator
+ if separator is None:
+ separator = ""
+ pass
+ else:
+ separator = str( separator )
+ pass
+ # prefix (if specified)
+ if prefix is not None:
+ filename.append( str( prefix ) )
+ pass
+ # additional keywords
+ ### check unsupported parameters
+ for kw in kwargs:
+ if kw not in supported and verbose():
+ print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
+ pass
+ pass
+ ### process supported keywords
+ for kw in supported:
+ if kw not in kwargs: continue
+ ### user name
+ if kw == 'with_username':
+ try:
+ # auto user name ?
+ if _try_bool( kwargs[kw] ): filename.append( getUserName() )
+ pass
+ except:
+ # user name given as parameter
+ filename.append( kwargs[kw] )
+ pass
+ pass
+ ### host name
+ elif kw == 'with_hostname':
+ try:
+ # auto host name ?
+ if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
+ pass
+ except:
+ # host name given as parameter
+ filename.append( kwargs[kw] )
+ pass
+ pass
+ ### port number
+ elif kw == 'with_port':
+ try:
+ # auto port number ?
+ if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
+ pass
+ except:
+ # port number given as parameter
+ filename.append( str( kwargs[kw] ) )
+ pass
+ pass
+ ### application name
+ elif kw == 'with_app':
+ try:
+ # auto application name ?
+ if _try_bool( kwargs[kw] ): filename.append( getAppName() )
+ pass
+ except:
+ # application name given as parameter
+ filename.append( kwargs[kw] )
+ pass
+ pass
+ pass
+ # suffix (if specified)
+ if suffix is not None:
+ filename.append( str( suffix ) )
+ pass
+ # raise an exception if file name is empty
+ if not filename:
+ raise Exception("Empty file name")
+ #
+ if extension is not None and extension.startswith("."): extension = extension[1:]
+ #
+ import os
+ name = separator.join( filename )
+ if hidden: name = "." + name # add dot for hidden files
+ if extension: name = name + "." + str( extension ) # add extension if defined
+ name = os.path.join( dir, name )
+ if unique:
+ # create unique file name
+ index = 0
+ while os.path.exists( name ):
+ index = index + 1
+ name = separator.join( filename ) + separator + str( index )
+ if hidden: name = "." + name # add dot for hidden files
+ if extension: name = name + "." + str( extension ) # add extension if defined
+ name = os.path.join( dir, name )
+ pass
+ pass
+ return name
# -----------------------------------------------------------------------------
-def get_config():
+def get_config(silent=False):
"""
Get list of modules, paths.
for module in modules_list :
module_variable=module+"_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 "********************************************************"
+ if not silent:
+ print "*******************************************************"
+ print "*"
+ print "* Environment variable",module_variable,"must be set"
+ print "* Module", module, "will be not available"
+ print "*"
+ print "********************************************************"
+ pass
to_remove_list.append(module)
continue
pass
# -----------------------------------------------------------------------------
-def set_env(args, modules_list, modules_root_dir):
+def set_env(args, modules_list, modules_root_dir, silent=False):
"""Add to the PATH-variables modules specific paths"""
python_version="python%d.%d" % sys.version_info[0:2]
salome_subdir,
"shared_modules"),
"PYTHONPATH")
- pass
- pass
+ # set environment for SMESH plugins
+ if module == "SMESH" :
+ os.environ["SMESH_MeshersList"]="StdMeshers"
+ if not os.environ.has_key("SALOME_StdMeshersResources"):
+ os.environ["SALOME_StdMeshersResources"] \
+ = modules_root_dir["SMESH"]+"/share/"+salome_subdir+"/resources/smesh"
+ pass
+ if args.has_key("SMESH_plugins"):
+ for plugin in args["SMESH_plugins"]:
+ plugin_root = ""
+ if os.environ.has_key(plugin+"_ROOT_DIR"):
+ plugin_root = os.environ[plugin+"_ROOT_DIR"]
+ else:
+ # workaround to avoid modifications of existing environment
+ if os.environ.has_key(plugin.upper()+"_ROOT_DIR"):
+ plugin_root = os.environ[plugin.upper()+"_ROOT_DIR"]
+ pass
+ pass
+ if plugin_root != "":
+ os.environ["SMESH_MeshersList"] \
+ = os.environ["SMESH_MeshersList"]+":"+plugin
+ if not os.environ.has_key("SALOME_"+plugin+"Resources"):
+ os.environ["SALOME_"+plugin+"Resources"] \
+ = plugin_root+"/share/"+salome_subdir+"/resources/"+plugin.lower()
+ add_path(os.path.join(plugin_root,get_lib_dir(),python_version, "site-packages",salome_subdir), "PYTHONPATH")
+ add_path(os.path.join(plugin_root,get_lib_dir(),salome_subdir), "PYTHONPATH")
+
+ if sys.platform == "win32":
+ add_path(os.path.join(plugin_root,get_lib_dir(),salome_subdir), "PATH")
+ else:
+ add_path(os.path.join(plugin_root,get_lib_dir(),salome_subdir), "LD_LIBRARY_PATH")
+ add_path(os.path.join(plugin_root,"bin",salome_subdir), "PYTHONPATH")
+ add_path(os.path.join(plugin_root,"bin",salome_subdir), "PATH")
+ pass
+ pass
+ pass
+ pass
+ pass
+
if sys.platform == 'win32':
os.environ["SALOMEPATH"]=";".join(modules_root_dir_list)
else:
if args['logger']:
os.environ["SALOME_trace"]="with_logger"
- # 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/"+salome_subdir+"/resources/smesh"
- pass
- if args.has_key("SMESH_plugins"):
- for plugin in args["SMESH_plugins"]:
- plugin_root = ""
- if os.environ.has_key(plugin+"_ROOT_DIR"):
- plugin_root = os.environ[plugin+"_ROOT_DIR"]
- else:
- # workaround to avoid modifications of existing environment
- if os.environ.has_key(plugin.upper()+"_ROOT_DIR"):
- plugin_root = os.environ[plugin.upper()+"_ROOT_DIR"]
- pass
- pass
- if plugin_root != "":
- os.environ["SMESH_MeshersList"] \
- = os.environ["SMESH_MeshersList"]+":"+plugin
- if not os.environ.has_key("SALOME_"+plugin+"Resources"):
- os.environ["SALOME_"+plugin+"Resources"] \
- = plugin_root+"/share/"+salome_subdir+"/resources/"+plugin.lower()
- add_path(os.path.join(plugin_root,get_lib_dir(),python_version,
- "site-packages",salome_subdir),
- "PYTHONPATH")
- add_path(os.path.join(plugin_root,get_lib_dir(),salome_subdir),
- "PYTHONPATH")
-
-
- if sys.platform == "win32":
- add_path(os.path.join(plugin_root,get_lib_dir(),salome_subdir),
- "PATH")
- else:
- add_path(os.path.join(plugin_root,get_lib_dir(),salome_subdir),
- "LD_LIBRARY_PATH")
- add_path(os.path.join(plugin_root,"bin",salome_subdir),
- "PYTHONPATH")
- add_path(os.path.join(plugin_root,"bin",salome_subdir),
- "PATH")
- pass
- pass
-
# set environment for SUPERV module
os.environ["ENABLE_MACRO_NODE"]="1"
# set resources variables if not yet set
salome_subdir,"resources","kernel")
if "GEOM" in modules_list:
- if verbose(): print "GEOM OCAF Resources"
+ if verbose() and not silent: print "GEOM OCAF Resources"
# set CSF_PluginDefaults variable only if it is not customized
# by the user
os.environ["CSF_GEOMDS_ResourcesDefaults"] \
= os.path.join(modules_root_dir["GEOM"],"share",
salome_subdir,"resources","geom")
- if verbose(): print "GEOM Shape Healing Resources"
+ if verbose() and not silent: print "GEOM Shape Healing Resources"
os.environ["CSF_ShHealingDefaults"] \
= os.path.join(modules_root_dir["GEOM"],"share",
salome_subdir,"resources","geom")
# -----------------------------------------------------------------------------
-def main():
- args, modules_list, modules_root_dir = get_config()
- set_env(args, modules_list, modules_root_dir)
+def main(silent=False):
+ args, modules_list, modules_root_dir = get_config(silent=silent)
+ set_env(args, modules_list, modules_root_dir, silent=silent)
return args
# -----------------------------------------------------------------------------
lib_LTLIBRARIES = libSalomeIDLKernel.la $(PAR_LIB)
nodist_libSalomeIDLKernel_la_SOURCES = $(IDL_SOURCES) $(DYNIDL_SRCS)
-libSalomeIDLKernel_la_CPPFLAGS =-I$(top_builddir)/salome_adm/unix \
+libSalomeIDLKernel_la_CPPFLAGS =-I$(top_builddir)/salome_adm/unix -include SALOMEconfig.h \
-I$(top_builddir)/idl \
@CORBA_CXXFLAGS@ @CORBA_INCLUDES@
libSalomeIDLKernel_la_LDFLAGS = -no-undefined -version-info=0:0:0
libSalomeIDLKernel_la_LIBADD = @CORBA_LIBS@
nodist_libSalomeParallelIDLKernel_la_SOURCES = $(PAR) $(GEN_PACO)
-libSalomeParallelIDLKernel_la_CPPFLAGS =-I$(top_builddir)/idl \
+libSalomeParallelIDLKernel_la_CPPFLAGS =-I$(top_builddir)/salome_adm/unix -include SALOMEconfig.h \
+ -I$(top_builddir)/idl \
@CORBA_CXXFLAGS@ @CORBA_INCLUDES@ \
@PACO_INCLUDES@
libSalomeParallelIDLKernel_la_LDFLAGS = -no-undefined -version-info=0:0:0
# rules for install and build (see make_common_starter.am)
salomeadmux_DATA = SALOMEconfig.h.in
salomeinclude_DATA = SALOMEconfig.h
-BUILT_SOURCES=SALOMEconfig.h SALOMEconfig.h.in
+BUILT_SOURCES=SALOMEconfig.ref SALOMEconfig.h SALOMEconfig.h.in
mostlyclean-local:
-rm -rf SALOMEconfig.h SALOMEconfig.h.in
# test if SALOMEconfig.ref has changed (contents), at build time
SALOMEconfig.h: $(top_builddir)/salome_adm/unix/SALOMEconfig.ref
@if ! [ -a $@ ]; then \
+ echo cp -p $< $@; \
cp -p $< $@; \
fi; \
- if ! cmp $< $@; then \
+ if ! cmp -s $< $@; then \
+ echo cp -p $< $@; \
cp -p $< $@; \
fi;
#undef PACKAGE_VERSION
#endif
+#ifdef _POSIX_C_SOURCE
+#undef _POSIX_C_SOURCE
+#endif
+
#endif
AC_CACHE_VAL(salome_cv_lib_occ,[
AC_TRY_LINK(
#include <TCollection_AsciiString.hxx>
-, size_t size;
- TCollection_AsciiString aStr ("toto");
+, TCollection_AsciiString aStr ("toto");
aStr.Capitalize();,
eval "salome_cv_lib_occ=yes",eval "salome_cv_lib_occ=no")
])
delete GENERIC_DESTRUCTOR::Destructors;
GENERIC_DESTRUCTOR::Destructors = 0;
+ atExitSingletonDone = false ;
DEVTRACE("HouseKeeping() very end ");
return ;
}
_sec = p_tm->tm_sec;
} else {
- char c;
+// char c;
// istringstream ist(s);
// ist >> _day >> c
// >> _month >> c
ostream & operator << (ostream & os, const Versatile & V)
{
Versatile::const_iterator it;
- char * sep = "";
+ const char * sep = "";
for(it=V.begin(); it!=V.end(); it++, sep=" ") {
string s = (*it)->affiche();
// Ask omniORBpy to transform SUPPORT (python Corba) ptr to IOR string
- PyObject* iorSupport = PyObject_CallMethod(orb, "object_to_string", "O", $input);
+ PyObject* iorSupport = PyObject_CallMethod(orb, (char*)"object_to_string", (char*)"O", $input);
if (iorSupport == Py_None)
return NULL;
// Ask omniORB to convert IOR string to SALOME::SenderDouble_ptr
int argc = 0;
- char *xargv = "";
+ char *xargv = (char*)"";
char **argv = &xargv;
CORBA::ORB_var ORB = CORBA::ORB_init(argc, argv);
CORBA::Object_var O = ORB->string_to_object(s);
// Ask omniORBpy to transform SUPPORT (python Corba) ptr to IOR string
- PyObject* iorSupport = PyObject_CallMethod(orb, "object_to_string", "O", $input);
+ PyObject* iorSupport = PyObject_CallMethod(orb, (char*)"object_to_string", (char*)"O", $input);
if (iorSupport == Py_None)
return NULL;
// Ask omniORB to convert IOR string to SALOME::SenderInt_ptr
int argc = 0;
- char *xargv = "";
+ char *xargv = (char*)"";
char **argv = &xargv;
CORBA::ORB_var ORB = CORBA::ORB_init(argc, argv);
CORBA::Object_var O = ORB->string_to_object(s);
PyObject* orb = PyDict_GetItemString(pdict, "o");
// Get the orb Corba C++
int argc = 0;
- char *xargv = "";
+ char *xargv = (char*)"";
char **argv = &xargv;
CORBA::ORB_var ORB = CORBA::ORB_init(argc, argv);
std::string s = ORB->object_to_string($1);
PyObject * tmp = PyString_FromString(s.c_str());
- $result = PyObject_CallMethod(orb, "string_to_object", "O", tmp);
+ $result = PyObject_CallMethod(orb, (char*)"string_to_object", (char*)"O", tmp);
}
%typemap(python,out) SALOME::SenderInt_ptr
PyObject* orb = PyDict_GetItemString(pdict, "o");
// Get the orb Corba C++
int argc = 0;
- char *xargv = "";
+ char *xargv = (char*)"";
char **argv = &xargv;
CORBA::ORB_var ORB = CORBA::ORB_init(argc, argv);
std::string s = ORB->object_to_string($1);
PyObject * tmp = PyString_FromString(s.c_str());
- $result = PyObject_CallMethod(orb, "string_to_object", "O", tmp);
+ $result = PyObject_CallMethod(orb, (char*)"string_to_object", (char*)"O", tmp);
}
PyObject * getValueForSenderDouble(SALOME::SenderDouble_ptr senderDouble);
int err = PyList_SetItem(py_list, i, Py_BuildValue("d", (double) ret[i]));
if(err)
{
- char * message = "Error in SUPPORT::getTypes";
+ const char * message = "Error in SUPPORT::getTypes";
PyErr_SetString(PyExc_RuntimeError, message);
return NULL;
}
int err = PyList_SetItem(py_list, i, Py_BuildValue("i", (int) ret[i]));
if(err)
{
- char * message = "Error in SUPPORT::getTypes";
+ const char * message = "Error in SUPPORT::getTypes";
PyErr_SetString(PyExc_RuntimeError, message);
return NULL;
}
int err = PyList_SetItem(tmpRow, j, Py_BuildValue("d", (double) ret[i*column+j]));
if(err)
{
- char * message = "PyList_SetItem matrix sent may be invalid";
+ const char * message = "PyList_SetItem matrix sent may be invalid";
PyErr_SetString(PyExc_RuntimeError, message);
return NULL;
}
delete _myConnexionToRegistry;
_myConnexionToRegistry = 0 ;
- _poa->deactivate_object(*_id) ;
- delete(_id) ;
+ if(_id)
+ delete(_id) ;
//SCRUTE(pd_refCount);
_thisObj->_remove_ref();
//SCRUTE(pd_refCount);
PyObject *globals = PyModule_GetDict(mainmod);
PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
PyObject *result = PyObject_CallMethod(pyCont,
- "import_component",
- "s",componentName);
+ (char*)"import_component",
+ (char*)"s",componentName);
int ret= PyInt_AsLong(result);
Py_XDECREF(result);
SCRUTE(ret);
PyObject *globals = PyModule_GetDict(mainmod);
PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
PyObject *result = PyObject_CallMethod(pyCont,
- "create_component_instance",
- "ssl",
+ (char*)"create_component_instance",
+ (char*)"ssl",
aCompName.c_str(),
instanceName.c_str(),
studyId);
}
else
{
- int count=10;
+ int count=20;
CORBA::Object_var obj = CORBA::Object::_nil() ;
while ( CORBA::is_nil(obj) && count )
{
{
MESSAGE("SALOME_Container::create_component_instance successful");
iobject=Engines::Component::_narrow(obj);
+ _listInstances_map[instanceName] = iobject;
return iobject._retn();
}
}
SCRUTE(aGenRegisterName);
SCRUTE(_cntInstances_map[aGenRegisterName]);
//SCRUTE(servant->pd_refCount);
+#if defined(_DEBUG_) || defined(_DEBUG)
bool ret_studyId = servant->setStudyId(studyId);
ASSERT(ret_studyId);
+#else
+ servant->setStudyId(studyId);
+#endif
// --- register the engine under the name
// containerName(.dir)/instanceName(.object)
#define _CONTAINER_INIT_PYTHON_HXX_
#include <SALOME_Container.hxx>
+#include <SALOMEconfig.h>
#include <pthread.h> // must be before Python.h !
#include <Python.h>
#define Py_ACQUIRE_NEW_THREAD \
PyEval_AcquireLock(); \
PyThreadState *myTstate = PyThreadState_New(KERNEL_PYTHON::_interp); \
- PyThreadState *myoldTstate = PyThreadState_Swap(myTstate);
+ PyThreadState_Swap(myTstate);
#define Py_RELEASE_NEW_THREAD \
PyEval_ReleaseThread(myTstate); \
def destroy(self):
MESSAGE( "SALOME_ComponentPy_i::destroy" )
- id = self._poa.servant_to_id(self)
- self._poa.deactivate_object(id)
+ #id = self._poa.servant_to_id(self)
+ #self._poa.deactivate_object(id)
+ return
#-------------------------------------------------------------------------
if (!isSupervContainer)
{
- int _argc = 1;
- char* _argv[] = {""};
+ // int _argc = 1;
+ // char* _argv[] = {""};
KERNEL_PYTHON::init_python(argc,argv);
}
else
PySys_SetArgv( argc , argv ) ;
}
- char *containerName = "";
+ char *containerName = (char *)"";
if(argc > 1)
{
containerName = argv[1] ;
system(aCommand.str().c_str());
#endif
- Engines_Container_i * myContainer
- = new Engines_Container_i(orb, root_poa, containerName , argc , argv );
+ new Engines_Container_i(orb, root_poa, containerName , argc , argv );
pman->activate();
if (!isSupervContainer)
{
- PyGILState_STATE gstate = PyGILState_Ensure();
+ PyGILState_Ensure();
//Delete python container that destroy orb from python (pyCont._orb.destroy())
Py_Finalize();
}
#-------------------------------------------------------------------------
- def __del__(self ):
- self._orb.destroy()
+ #def __del__(self ):
+ # self._orb.destroy()
def import_component(self, componentName):
MESSAGE( "SALOME_Container_i::import_component" )
CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
if ( !CORBA::is_nil(obj) )
{
- // unregister the registered container if it exists
- _NS->Destroy_Name(containerNameInNS.c_str());
- // unregister component instances ???
- //Engines::Container_var cont=Engines::Container::_narrow(obj);
+ // shutdown the registered container if it exists
+ Engines::Container_var cont=Engines::Container::_narrow(obj);
+ if(!CORBA::is_nil(cont))
+ {
+ try
+ {
+ cont->Shutdown();
+ }
+ catch(CORBA::Exception&)
+ {
+ INFOS("CORBA::Exception ignored.");
+ }
+ }
}
//redirect stdout and stderr in a file
SALOME_ModuleCatalog::Acomponent_var compoInfo = Catalog->GetComponent(compoi);
if (CORBA::is_nil (compoInfo))
{
- INFOS("ContainerManager Error: Component not found in the catalog" );
- INFOS( compoi );
- return Engines::Container::_nil();
+ continue;
}
SALOME_ModuleCatalog::ImplType impl=compoInfo->implementation_type();
container_exe=compoInfo->implementation_name();
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#include <SALOMEconfig.h>
#include <stdexcept>
#include <omniORB4/CORBA.h>
+
#include "utilities.h"
// CCRT porting
_container = Engines::Container::_duplicate(container);
_origFileName = origFileName;
_machine = GetHostname();
+#if defined(_DEBUG_) || defined(_DEBUG)
int OK = addRef(_machine.c_str(), _origFileName.c_str());
SCRUTE(OK);
+#else
+ addRef(_machine.c_str(), _origFileName.c_str());
+#endif
}
aBlock = _fileDistributedSource[file_name]->getBlock(fileId);
toFollow = aBlock->length();
CORBA::Octet *buf = aBlock->get_buffer();
+#if defined(_DEBUG_) || defined(_DEBUG)
int nbWri = fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
ASSERT(nbWri == toFollow);
+#else
+ fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
+#endif
delete aBlock;
}
fclose(fp);
cout << "Test started " << endl;
DF_Application* appli = new DF_Application;
+ /*
DF_Document* doc1 = appli->NewDocument("doc_1");
- /*
DF_Label root1 = doc1->Main();
DF_Label child = root1.FindChild(3, true); //0:1:3
};
omniORBpyAPI* api;
+ PyObject* dsc ;
%}
PyObject* pyapi = PyObject_GetAttrString(omnipy, (char*)"API");
api = (omniORBpyAPI*)PyCObject_AsVoidPtr(pyapi);
Py_DECREF(pyapi);
+
+ PyObject* engines = PyImport_ImportModule("Engines");
+ dsc = PyObject_GetAttrString(engines, "DSC");
%}
%include <exception.i>
#ifdef WITH_NUMPY
/* With Numpy */
+#ifdef HAVE_ISINF
+#undef HAVE_ISINF
+#endif
#include <numpy/arrayobject.h>
typedef PyArrayObject ArrayObject;
/* Given a PyObject, return a string describing its type.
*/
-char* pytype_string(PyObject* py_obj) {
+const char* pytype_string(PyObject* py_obj) {
if (py_obj == NULL ) return "C NULL value";
if (PyCallable_Check(py_obj)) return "callable" ;
if (PyString_Check( py_obj)) return "string" ;
/* Given a Numeric typecode, return a string describing the type.
*/
-char* typecode_string(int typecode) {
- char* type_names[] = {"bool","byte","unsigned byte","short",
+const char* typecode_string(int typecode) {
+ const char* type_names[] = {"bool","byte","unsigned byte","short",
"unsigned short","int","unsigned int","long","unsigned long",
"longlong","unsigned longlong",
"float","double","long double","complex float","complex double","complex long double",
ary = (PyArrayObject*) input;
}
else if is_array(input) {
- char* desired_type = typecode_string(typecode);
- char* actual_type = typecode_string(array_type(input));
+ const char* desired_type = typecode_string(typecode);
+ const char* actual_type = typecode_string(array_type(input));
PyErr_Format(PyExc_TypeError,
"Array of type '%s' required. Array of type '%s' given",
desired_type, actual_type);
ary = NULL;
}
else {
- char * desired_type = typecode_string(typecode);
- char * actual_type = pytype_string(input);
+ const char * desired_type = typecode_string(typecode);
+ const char * actual_type = pytype_string(input);
PyErr_Format(PyExc_TypeError,
"Array of type '%s' required. A %s was given",
desired_type, actual_type);
%define TYPEMAP_IN3(type,typecode)
%typemap(in) type* IN_ARRAY3
(ArrayObject* array=NULL, int is_new_object) {
- int size[1] = {-1};
if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor,0)) == -1)
{
%#ifdef WITH_NUMPY
+ int size[1] = {-1};
array = obj_to_array_contiguous_allow_conversion($input, typecode, &is_new_object);
if (!array || !require_dimensions(array,1) || !require_size(array,size,1)) SWIG_fail;
$1 = (type*) array->data;
/* Specific typemap for complex */
%typemap(in) float* ecpval
(ArrayObject* array=NULL, int is_new_object) {
- int size[1] = {-1};
if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor,0)) == -1)
{
%#ifdef WITH_NUMPY
+ int size[1] = {-1};
array = obj_to_array_contiguous_allow_conversion($input, PyArray_CFLOAT, &is_new_object);
if (!array || !require_dimensions(array,1) || !require_size(array,size,1)) SWIG_fail;
$1 = (float*) array->data;
/* array of strings on input */
%typemap(in) char** eval
(ArrayObject* array=NULL, int is_new_object) {
- int size[1] = {-1};
stringArray* sarray;
if ((SWIG_ConvertPtr($input, (void **) &sarray, $descriptor(stringArray *),0)) == -1)
{
%#ifdef WITH_NUMPY
+ int size[1] = {-1};
array = obj_to_array_contiguous_allow_conversion($input, PyArray_STRING, &is_new_object);
if (!array || !require_dimensions(array,1) || !require_size(array,size,1)) SWIG_fail;
$1 = (char**) malloc(array_size(array,0)*sizeof(char*));
if (!temp || !require_contiguous(temp)) SWIG_fail;
$1 = (type*) temp->data;
%#else
+ temp = NULL;
SWIG_exception(SWIG_TypeError, "type* expected");
%#endif
}
if (!temp || !require_contiguous(temp)) SWIG_fail;
$1 = (float*) temp->data;
%#else
+ temp = NULL;
SWIG_exception(SWIG_TypeError, "complex array expected");
%#endif
}
for(int i=0;i<array_size(temp,0);i++)
$1[i]=(char*) temp->data+i*temp->strides[0];
%#else
+ temp = NULL;
SWIG_exception(SWIG_TypeError, "string array expected");
%#endif
}
{
$1=(CORBA::Boolean)PyInt_AsLong($input);
}
+%typemap(out) CORBA::Boolean
+{
+ $result=PyInt_FromLong($1 ? 1 : 0);
+}
%define CORBAPTR(type)
%typemap(in) type##_ptr
}
catch(Engines::DSC::PortNotDefined& _e) {
Py_BLOCK_THREADS
- PyErr_SetString(PyExc_ValueError,"Port not defined");
+ PyObject* excc = PyObject_GetAttrString(dsc, "PortNotDefined");
+ PyObject* exci = PyEval_CallObject(excc, (PyObject *)NULL);
+ PyErr_SetObject(excc, exci);
+ Py_XDECREF(excc);
+ Py_XDECREF(exci);
return NULL;
}
catch(Engines::DSC::PortNotConnected& _e) {
Py_BLOCK_THREADS
- PyErr_SetString(PyExc_ValueError,"Port not connected");
+ PyObject* excc = PyObject_GetAttrString(dsc, "PortNotConnected");
+ PyObject* exci = PyEval_CallObject(excc, (PyObject *)NULL);
+ PyErr_SetObject(excc, exci);
+ Py_XDECREF(excc);
+ Py_XDECREF(exci);
return NULL;
}
catch(Engines::DSC::BadPortType& _e) {
Py_BLOCK_THREADS
- PyErr_SetString(PyExc_ValueError,"Bad port type");
+ PyObject* excc = PyObject_GetAttrString(dsc, "BadPortType");
+ PyObject* exci = PyEval_CallObject(excc, (PyObject *)NULL);
+ PyErr_SetObject(excc, exci);
+ Py_XDECREF(excc);
+ Py_XDECREF(exci);
return NULL;
}
catch (SALOME_Exception &e) {
}
catch (SALOME::SALOME_Exception &e) {
Py_BLOCK_THREADS
+ //This one should be converted into a python corba exception
PyErr_SetString(PyExc_RuntimeError,e.details.text);
return NULL;
}
virtual void add_provides_port(Ports::Port_ptr ref, const char* provides_port_name, Ports::PortProperties_ptr port_prop);
virtual void add_uses_port(const char* repository_id, const char* uses_port_name, Ports::PortProperties_ptr port_prop);
virtual Engines::DSC::uses_port * get_uses_port(const char* uses_port_name);
+ CORBA::Boolean is_connected(const char* port_name) throw (Engines::DSC::PortNotDefined);
// End of DSC interface for python components
};
+#include <boost/type_traits/remove_all_extents.hpp>
namespace CalciumInterface {
/********************* INTERFACE DE DECONNEXION *****************/
+ static inline void
+ ecp_cd (Superv_Component_i & component, std::string & instanceName)
+ {
+ /* TODO : Trouver le nom de l'instance SALOME*/
+ if (instanceName.empty()) instanceName="UNDEFINED";
+
+ }
+
static void
ecp_fin (Superv_Component_i & component, bool provideLastGivenValue)
{
/********************* INTERFACES DE LECTURE *****************/
- // T1 est le type de données
- template <typename T1 > static void
- ecp_lecture ( Superv_Component_i & component,
- CalciumTypes::DependencyType dependencyType,
- double & ti,
- double const & tf,
- long & i,
- const string & nomVar,
- size_t bufferLength,
- size_t & nRead,
- T1 * &data )
- {
- ecp_lecture<T1,T1> (component,dependencyType,ti,tf,
- i,nomVar,bufferLength,nRead,data);
-
- }
// T1 est le type de données
// T2 est un <nom> de type Calcium permettant de sélectionner le port CORBA correspondant
// le port à utiliser est le port cplx
template <typename T1, typename T2 > static void
ecp_lecture ( Superv_Component_i & component,
- CalciumTypes::DependencyType dependencyType,
+ int const & dependencyType,
double & ti,
double const & tf,
long & i,
typedef typename PortType::DataManipulator DataManipulator;
typedef typename DataManipulator::Type CorbaDataType; // Attention != T1
typedef typename DataManipulator::InnerType InnerType;
-
+ CalciumTypes::DependencyType _dependencyType=
+ static_cast<CalciumTypes::DependencyType>(dependencyType);
+
CorbaDataType corbaData;
#ifdef _DEBUG_
LOC(OSS()<<"Le mode de dépendance de la variable "
<< nomVar << " est indéfini."));
- if ( ( portDependencyType != dependencyType ) &&
- ( dependencyType != CalciumTypes::SEQUENCE_DEPENDENCY ) )
+ if ( ( portDependencyType != _dependencyType ) &&
+ ( _dependencyType != CalciumTypes::SEQUENCE_DEPENDENCY ) )
throw CalciumException(CalciumTypes::CPITVR,
LOC(OSS()<<"Le mode de dépendance de la variable "
<< nomVar << ": " << portDependencyType
<< " ne correspond pas au mode demandé."));
- if ( dependencyType == CalciumTypes::TIME_DEPENDENCY ) {
+ if ( _dependencyType == CalciumTypes::TIME_DEPENDENCY ) {
corbaData = port->get(ti,tf, 0);
#ifdef _DEBUG_
std::cout << "-------- CalciumInterface(ecp_lecture) MARK 5 ------------------" << std::endl;
#endif
}
- else if ( dependencyType == CalciumTypes::ITERATION_DEPENDENCY ) {
+ else if ( _dependencyType == CalciumTypes::ITERATION_DEPENDENCY ) {
corbaData = port->get(0, i);
#ifdef _DEBUG_
std::cout << "-------- CalciumInterface(ecp_lecture) MARK 6 ------------------" << std::endl;
return;
}
+ // T1 est le type de données
+ template <typename T1 > static void
+ ecp_lecture ( Superv_Component_i & component,
+ int const & dependencyType,
+ double & ti,
+ double const & tf,
+ long & i,
+ const string & nomVar,
+ size_t bufferLength,
+ size_t & nRead,
+ T1 * &data )
+ {
+ ecp_lecture<T1,T1> (component,dependencyType,ti,tf,
+ i,nomVar,bufferLength,nRead,data);
+
+ }
/********************* INTERFACES D'ECRITURE *****************/
- template <typename T1> static void
- ecp_ecriture ( Superv_Component_i & component,
- CalciumTypes::DependencyType dependencyType,
- double const & t,
- long const & i,
- const string & nomVar,
- size_t bufferLength,
- T1 & data ) {
- ecp_ecriture<T1,T1> (component,dependencyType,t,i,nomVar,bufferLength,data);
- }
-
+ // T1 : DataType
+ // T2 : PortType
template <typename T1, typename T2> static void
ecp_ecriture ( Superv_Component_i & component,
- CalciumTypes::DependencyType dependencyType,
+ int const & dependencyType,
double const & t,
long const & i,
const string & nomVar,
size_t bufferLength,
- T1 & data )
+ T1 const & data )
{
assert(&component);
- //typedef typename StarTrait<TT>::NonStarType T;
- typedef typename UsesPortTraits<T2>::PortType PortType;
- typedef typename ProvidesPortTraits<T2>::PortType ProvidesPortType;
- typedef typename ProvidesPortType::DataManipulator DataManipulator;
+ //typedef typename StarTrait<TT>::NonStarType T;
+ typedef typename boost::remove_all_extents< T2 >::type T2_without_extent;
+ typedef typename boost::remove_all_extents< T1 >::type T1_without_extent;
+
+ typedef typename UsesPortTraits <T2_without_extent>::PortType UsesPortType;
+ typedef typename ProvidesPortTraits<T2_without_extent>::PortType ProvidesPortType;// pour obtenir un manipulateur de données
+ typedef typename ProvidesPortType::DataManipulator DataManipulator;
// Verifier que l'on peut définir UsesPortType::DataManipulator
// typedef typename PortType::DataManipulator DataManipulator;
- typedef typename DataManipulator::Type CorbaDataType; // Attention != T1
- typedef typename DataManipulator::InnerType InnerType;
+ typedef typename DataManipulator::Type CorbaDataType; // Attention != T1
+ typedef typename DataManipulator::InnerType InnerType;
+
+ T1_without_extent const & _data = data;
+
+ CalciumTypes::DependencyType _dependencyType=
+ static_cast<CalciumTypes::DependencyType>(dependencyType);
#ifdef _DEBUG_
std::cerr << "-------- CalciumInterface(ecriture) MARK 1 ------------------" << std::endl;
#endif
if ( nomVar.empty() ) throw CalciumException(CalciumTypes::CPNMVR,
LOC("Le nom de la variable est <nul>"));
- PortType * port;
+ UsesPortType * port;
#ifdef _DEBUG_
std::cout << "-------- CalciumInterface(ecriture) MARK 2 ------------------" << std::endl;
#endif
try {
- port = component.Superv_Component_i::get_port< PortType > (nomVar.c_str());
+ port = component.Superv_Component_i::get_port< UsesPortType > (nomVar.c_str());
#ifdef _DEBUG_
std::cout << "-------- CalciumInterface(ecriture) MARK 3 ------------------" << std::endl;
#endif
// throw (CalciumException(CalciumTypes::CPIT,ex));
// }
- if ( dependencyType == CalciumTypes::UNDEFINED_DEPENDENCY )
+ if ( _dependencyType == CalciumTypes::UNDEFINED_DEPENDENCY )
throw CalciumException(CalciumTypes::CPIT,
LOC(OSS()<<"Le mode de dépendance demandé pour la variable "
<< nomVar << " est indéfini."));
- if ( dependencyType == CalciumTypes::SEQUENCE_DEPENDENCY )
+ if ( _dependencyType == CalciumTypes::SEQUENCE_DEPENDENCY )
throw CalciumException(CalciumTypes::CPIT,
LOC(OSS()<<"Le mode de dépendance SEQUENCE_DEPENDENCY pour la variable "
<< nomVar << " est impossible en écriture."));
// et vice-versa pour informer les provides port du mode dans lequel on est. Sinon il faut
// modifier l'interface IDL pour y ajouter un mode de dépendance !
// ---->
-// if ( portDependencyType != dependencyType )
+// if ( portDependencyType != _dependencyType )
// throw CalciumException(CalciumTypes::CPITVR,
// LOC(OSS()<<"Le mode de dépendance de la variable "
// << nomVar << " ne correspond pas au mode demandé."));
// OLD : la séquence locale. Or la méthode put récupère le buffer directement
// OLD : qui est alors le buffer utilisateur. Il pourrait alors arriver que :
// OLD : * Le recepteur efface le buffer emetteur
- // OLD : * Le port lui-même efface le buffer de l'ulisateur !
+ // OLD : * Le port lui-même efface le buffer de l'utilisateur !
// OLD : Cette copie est effectuée dans GenericPortUses::put
// OLD : en fonction de la collocalisation ou non.
// - OLD :En cas de connection multiples d'un port uses distant vers plusieurs port provides
// OLD : Il faut effectuer une copie dans le port provides.
// OLD : Cette copie est effectuée dans GenericPortUses::put
// OLD : en fonction de la collocalisation ou non.
- Copy2CorbaSpace<IsSameType<T1,InnerType>::value, DataManipulator >::apply(corbaData,data,bufferLength);
+ Copy2CorbaSpace<IsSameType<T1_without_extent,InnerType>::value, DataManipulator >::apply(corbaData,_data,bufferLength);
//TODO : GERER LES EXCEPTIONS ICI : ex le port n'est pas connecté
- if ( dependencyType == CalciumTypes::TIME_DEPENDENCY ) {
+ if ( _dependencyType == CalciumTypes::TIME_DEPENDENCY ) {
try
{
port->put(*corbaData,t, -1);
std::cout << "-------- CalciumInterface(ecriture) MARK 5 ------------------" << std::endl;
#endif
}
- else if ( dependencyType == CalciumTypes::ITERATION_DEPENDENCY ) {
+ else if ( _dependencyType == CalciumTypes::ITERATION_DEPENDENCY ) {
try
{
port->put(*corbaData,-1, i);
#endif
return;
- }
+ };
+
+ template <typename T1> static void
+ ecp_ecriture ( Superv_Component_i & component,
+ int const & dependencyType,
+ double const & t,
+ long const & i,
+ const string & nomVar,
+ size_t bufferLength,
+ T1 const & data ) {
+ ecp_ecriture<T1,T1> (component,dependencyType,t,i,nomVar,bufferLength,data);
+ };
};
public virtual POA_Ports::PortProperties, \
public GenericProvidesPort< __VA_ARGS__ , CalciumCouplingPolicy, calcium_provides_port > { \
private : \
- omni_semaphore _mustnotdisconnectyet; \
+ omni_mutex _disconnect_mutex; \
+ int _mustnotdisconnect; \
public : \
typedef __VA_ARGS__ DataManipulator; \
typedef DataManipulator::Type CorbaDataType; \
typedef GenericPort< DataManipulator , \
CalciumCouplingPolicy > Port; \
+ specificPortName () : _mustnotdisconnect(0) {}; \
\
- specificPortName () :_mustnotdisconnectyet(0) {}; \
- \
virtual ~ specificPortName (); \
\
inline void disconnect(bool provideLastGivenValue) { \
- if (! _mustnotdisconnectyet.trywait() ) { \
- Port::disconnect(provideLastGivenValue); \
- } \
- } \
+ _disconnect_mutex.lock(); \
+ if(_mustnotdisconnect > 1) \
+ { \
+ _mustnotdisconnect--; \
+ } \
+ else if(_mustnotdisconnect == 1) \
+ { \
+ _mustnotdisconnect--; \
+ Port::disconnect(provideLastGivenValue); \
+ } \
+ _disconnect_mutex.unlock(); \
+ } \
inline void setDependencyType(CalciumTypes::DependencyType dependencyType) { \
Port::setDependencyType(dependencyType); \
} \
virtual void provides_port_changed(int connection_nbr, \
const Engines::DSC::Message message) { \
if ( message == Engines::DSC::AddingConnection) \
- _mustnotdisconnectyet.post(); \
+ { \
+ _disconnect_mutex.lock(); \
+ _mustnotdisconnect++; \
+ _disconnect_mutex.unlock(); \
+ } \
else if ( message == Engines::DSC::RemovingConnection ) \
- disconnect(false); \
+ { \
+ disconnect(false); \
+ } \
} \
}; \
#ifndef _CALCIUM_INTERFACE_HXX_
#define _CALCIUM_INTERFACE_HXX_
-//Interface C++
+//Interface CALCIUM des utilisateurs en C++
#include "CalciumCxxInterface.hxx"
#include "CalciumException.hxx"
#include <stdio.h>
+//Ce fichier déclare et défini l'interfaçage entre l'API utilisteur C et C++
+//Les procédures déclarées n'ont pas vocation à être utilisées directement (celà est
+// cependant possible).
//#define _DEBUG_
#ifdef _DEBUG_
double _tf=*tf; \
size_t _nRead=0; \
size_t _bufferLength=bufferLength; \
- CalciumTypes::DependencyType _dependencyType= \
- static_cast<CalciumTypes::DependencyType>(dependencyType); \
\
if ( IsSameType< _name , cplx >::value ) _bufferLength*=2; \
DEBTRACE( "-------- CalciumInterface(lecture Inter Part) MARK 1 ------------------" ) \
try { \
CalciumInterface::ecp_lecture< _type, _name >( *_component, \
- _dependencyType, \
+ dependencyType, \
_ti, _tf, *i, \
nomvar, \
_bufferLength, _nRead, *data); \
} catch ( const CalciumException & ex) { \
DEBTRACE( ex.what() ); \
return ex.getInfo(); \
- } catch ( ... ) { \
- std::cerr << "Unexpected exception " << std::endl; \
- return CalciumTypes::CPATAL; \
+ } catch ( ... ) { \
+ std::cerr << "Unexpected exception " << std::endl; \
+ return CalciumTypes::CPATAL; \
} \
if ( IsSameType< _name , cplx >::value ) { *nRead=_nRead/2; \
DEBTRACE( "-------- CalciumInterface(lecture Inter Part) IsSameType cplx -------------" ) \
DEBTRACE( "-------- CalciumInterface(lecture Inter Part) _nRead : " << _nRead ) \
DEBTRACE( "-------- CalciumInterface(lecture Inter Part) *nRead : " << *nRead ) \
} else *nRead = _nRead; \
- if (_dependencyType == CalciumTypes::CP_SEQUENTIEL ) \
+ if (dependencyType == CalciumTypes::CP_SEQUENTIEL ) \
*ti=(CalTimeType< _type _qual >::TimeType)(_ti); \
DEBTRACE( "-------- CalciumInterface(lecture Inter Part), Data Ptr :" << *data ) \
return CalciumTypes::CPOK; \
DEBTRACE( "-------- CalciumInterface(ecriture Inter Part) MARK 1 ------------------" ) \
try { \
/*printf("-------- CalciumInterface(ecriture Inter Part), cp_name : Nom de la var. de type %s : %s\n",#_type,nomvar);*/ \
- std::string essai(nomvar); \
- DEBTRACE( "----------->-" << nomvar ) \
+ DEBTRACE( "----------->-" << nomvar ) \
CalciumInterface::ecp_ecriture< _type, _name >( *_component, \
- static_cast<CalciumTypes::DependencyType>(dependencyType), \
+ dependencyType, \
_t,i,nomvar,_bufferLength,*data); \
} catch ( const CalciumException & ex) { \
std::cerr << ex.what() << std::endl; \
// double _tf=*tf;
// size_t _nRead=0;
// size_t _bufferLength=bufferLength;
-// CalciumTypes::DependencyType _dependencyType=
+// CalciumTypes::DependencyType dependencyType=
// static_cast<CalciumTypes::DependencyType>(dependencyType);
// // - GERER POINTEUR NULL : NOTHING TODO
// DEBTRACE( "-------- CalciumInterface(lecture Inter Part) MARK 1 ------------------" )
// try {
// CalciumInterface::ecp_lecture< char*, char* >( *_component,
-// _dependencyType,
+// dependencyType,
// _ti, _tf, *i,
// nomvar,
// _bufferLength, _nRead, *data);
// *nRead = _nRead;
-// if (_dependencyType == CalciumTypes::CP_SEQUENTIEL )
+// if (dependencyType == CalciumTypes::CP_SEQUENTIEL )
// *ti=(float)(_ti);
// DEBTRACE( "-------- CalciumInterface(lecture Inter Part), Data Ptr :" << *data ) ;
#include "Superv_Component_i.hxx"
// PROVIDES PORT TRAITS
-struct UnknownProvidesPortType {};
+template <class T> struct UnknownProvidesPortType {};
+
template <class T> struct ProvidesPortTraits {
- typedef UnknownProvidesPortType PortType;
+ typedef UnknownProvidesPortType<T> PortType;
};
template <> struct ProvidesPortTraits<int> {
typedef calcium_integer_port_provides PortType;
// USES PORT TRAITS
-struct UnknownUsesPortType {};
+template <class T> struct UnknownUsesPortType {};
template <class T> struct UsesPortTraits {
- typedef UnknownUsesPortType PortType;
+ typedef UnknownUsesPortType<T> PortType;
};
template <> struct UsesPortTraits<int> {
typedef calcium_integer_port_uses PortType;
struct Copy2CorbaSpace {
template <class T1, class T2>
- static void apply( T1 * & corbaData, T2 & data, size_t nRead){
+ static void apply( T1 * & corbaData, T2 const & data, size_t nRead){
typedef typename ProvidesPortTraits<T2>::PortType PortType;
//typedef typename UsesPortTraits<T2>::PortType PortType;
-//ESSAI: typedef typename PortType::DataManipulator DataManipulator;
+ //ESSAI: typedef typename PortType::DataManipulator DataManipulator;
typedef typename DataManipulator::InnerType InnerType;
#ifdef _DEBUG_
std::cerr << "-------- Copy2CorbaSpace<true> MARK 1 ------------------" << std::endl;
#endif
- // Crée le type corba à partir du data sans lui en donner la propriété
- corbaData = DataManipulator::create(nRead,&data,false);
+ // Crée le type corba à partir du data sans lui en donner la propriété.
+ // Le const_cast supprime le caractère const du type T2 const & de data car
+ // DataManipulator::create n'a pas le caractère const sur son paramètre data pour le
+ // cas de figure où la propriété de la donnée lui est donnée.
+ corbaData = DataManipulator::create(nRead,const_cast<T2 * > (&data),false);
#ifdef _DEBUG_
std::cerr << "-------- Copy2CorbaSpace<true> MARK 2 --(dataPtr : "
<< DataManipulator::getPointer(corbaData,false)<<")----------------" << std::endl;
Copy2CorbaSpace<false, DataManipulator> {
template <class T1, class T2>
- static void apply( T1 * & corbaData, T2 & data, size_t nRead){
+ static void apply( T1 * & corbaData, T2 const & data, size_t nRead){
typedef typename ProvidesPortTraits<T2>::PortType PortType;
// typedef typename UsesPortTraits<T2>::PortType PortType;
-I$(top_srcdir)/src/Utils \
-I$(top_srcdir)/src/Container \
-I$(top_srcdir)/src/Notification \
- -I$(top_builddir)/salome_adm/unix \
+ -I$(top_builddir)/salome_adm/unix -include SALOMEconfig.h \
-I$(top_builddir)/idl \
@CORBA_CXXFLAGS@ @CORBA_INCLUDES@ @BOOST_CPPFLAGS@
std::cout << "------------ TEST1 --------------" << std::endl;
- int ret=0;
+ // int ret=0;
CORBA::Long time=1,tag=1;
typedef PalmCouplingPolicy::DataIdContainer DataIdContainer;
std::cout << "------------ TEST2 --------------" << std::endl;
- int ret=0;
+ // int ret=0;
CORBA::Long time=1,tag=1;
typedef PalmCouplingPolicy::DataIdContainer DataIdContainer;
// Author : Eric Fayolle (EDF)
// Module : KERNEL
void fake_method(void) {
-int fake_int;
+ // int fake_int;
};
throw HDFexception("Can't identify an internal object");
}
-int HDFfile::ExistInternalObject(char *object_name)
+int HDFfile::ExistInternalObject(const char *object_name)
{
int n,i;
int ret = 0;
int nInternalObjects();
void InternalObjectIndentify(int rank, char *object_name);
- int ExistInternalObject(char *object_name);
+ int ExistInternalObject(const char *object_name);
hdf_object_type InternalObjectType(char *object_name);
int nAttributes();
throw HDFexception("Can't identify an internal object");
}
-int HDFgroup::ExistInternalObject(char *object_name)
+int HDFgroup::ExistInternalObject(const char *object_name)
{
int n,i;
int ret = 0;
int nInternalObjects();
void InternalObjectIndentify(int rank, char *object_name);
- int ExistInternalObject(char *object_name);
+ int ExistInternalObject(const char *object_name);
hdf_object_type InternalObjectType(char *object_name);
int nAttributes();
hdf_err Num(hdf_idt id,const char *name, void *data);
hdf_err
-HDFnObjects(hdf_idt fid,char *path,int *n)
+HDFnObjects(hdf_idt fid,const char *path,int *n)
{
int idx;
int m = 0;
{
#include "HDFtypes.h"
}
-#include <HDFexport.hxx>
+#include "HDFexport.hxx"
class HDF_EXPORT HDFobject {
protected :
hdf_err RankInfo(hdf_idt id, const char *name, void *data);
-hdf_err HDFobjectIdentify(hdf_idt fid,char *path,int i,char *name)
+hdf_err HDFobjectIdentify(hdf_idt fid,const char *path,int i,char *name)
{
int idx;
extern
hdf_err
-HDFnObjects(hdf_idt fid,char *path,int *n);
+HDFnObjects(hdf_idt fid,const char *path,int *n);
extern
-hdf_err HDFobjectIdentify(hdf_idt fid,char *path,int i,char *name);
+hdf_err HDFobjectIdentify(hdf_idt fid,const char *path,int i,char *name);
extern
hdf_err HDFobjectType(hdf_idt id, char *name, hdf_object_type *type);
{
std::stringstream exec;
exec << "$DEBUGGER SALOME_LauncherServer " << getpid() << "&";
- std::cerr << exec.str() << std::endl;
+ MESSAGE ( exec.str() );
system(exec.str().c_str());
while(1);
}
void terminateHandler(void)
{
- std::cerr << "Terminate: not managed exception !" << std::endl;
+ MESSAGE ( "Terminate: not managed exception !" );
AttachDebugger();
}
void unexpectedHandler(void)
{
- std::cerr << "Unexpected: unexpected exception !" << std::endl;
+ MESSAGE ( "Unexpected: unexpected exception !" );
AttachDebugger();
}
toFollow = aBlock->length();
SCRUTE(toFollow);
CORBA::Octet *buf = aBlock->get_buffer();
+#if defined(_DEBUG_) || defined(_DEBUG)
int nbWri = fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
- delete aBlock;
ASSERT(nbWri == toFollow);
+#else
+ fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
+#endif
+ delete aBlock;
}
fclose(fp);
MESSAGE("end of transfer");
// be sure to have an instance of traceCollector, when used via SWIG
// in a Python module
int argc = 0;
- char *xargv = "";
+ char *xargv = (char*)"";
char **argv = &xargv;
CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);
// LocalTraceCollector *myThreadTrace = SALOMETraceCollector::instance(orb);
bp1->deleteInstance(bp1);
// --- trace on file
- char *theFileName = TRACEFILE;
+ const char *theFileName = TRACEFILE;
string s = "file:";
s += theFileName;
// --- Get or initialize the orb
int _argc = 1;
- char* _argv[] = {""};
+ char* _argv[] = {(char*)""};
ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance() ;
ASSERT(SINGLETON_<ORB_INIT>::IsAlreadyExisting());
_orb = init(_argc , _argv ) ;
#define AFX_LOGGER_H__96F2A3AB_F6F8_11D6_BFA6_000476A0958C__INCLUDED_
#include <strstream>
+#include <SALOMEconfig.h>
#include "Logger.hh"
//these declarations for files don't using OCC includes (for example HDF)
#include "utilities.h"
#ifdef _DEBUG_
-static int MYDEBUG = 1;
+static int MYDEBUG = 0;
#else
-static int MYDEBUG = 1;
+static int MYDEBUG = 0;
#endif
static const char* SEPARATOR = "::";
if (aDoc != NULL)
handler->ProcessXmlDocument(aDoc);
else
- INFOS("ModuleCatalog: could not parse file "<<file);
+ MESSAGE("ModuleCatalog: could not parse file "<<file);
xmlFreeDoc(aDoc);
xmlCleanupParser();
fclose(aFile);
}
else
- INFOS("ModuleCatalog: file "<<file<<" is not readable.");
+ MESSAGE("ModuleCatalog: file "<<file<<" is not readable.");
delete handler;
CosNaming::Name context_name;
vector<string> splitPath;
- int dimension_resultat = _createContextNameDir(Path,
+ _createContextNameDir(Path,
context_name,
splitPath,
false);
// SCRUTE(path);
CosNaming::Name context_name;
vector<string> splitPath;
- int dimension_resultat = _createContextNameDir(path.c_str(),
+ _createContextNameDir(path.c_str(),
context_name,
splitPath,
true);
import time
from omniORB import CORBA
import CosNaming
+import string
from string import *
from SALOME_utilities import *
#delete first '/' before split
Path=Path[1:]
- result_resolve_path = split(Path,'/')
+ result_resolve_path = string.split(Path,'/')
if len(result_resolve_path)>1:
# A directory is treated (not only an object name)
# We had to test if the directory where ObjRef should be recorded
#delete first '/' before split
Path=Path[1:]
- result_resolve_path = split(Path,'/')
+ result_resolve_path = string.split(Path,'/')
_context_name=[]
for i in range(len(result_resolve_path)-1):
_context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir"))
#delete first '/' before split
Path=Path[1:]
- result_resolve_path = split(Path,'/')
+ result_resolve_path = string.split(Path,'/')
_context_name = []
for i in range(len(result_resolve_path)):
_context_name[CosNaming.NameComponent(result_resolve_path[i],"dir")]
MESSAGE ( "Create_Directory : CosNaming.NamingContext.CannotProceed" )
except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
MESSAGE ( "Create_Directory : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )
-
-
-
+ def Destroy_Name(self,Path):
+ resolve_path=string.split(Path,'/')
+ if resolve_path[0] == '': del resolve_path[0]
+ dir_path=resolve_path[:-1]
+ context_name=[]
+ for e in dir_path:
+ context_name.append(CosNaming.NameComponent(e,"dir"))
+ context_name.append(CosNaming.NameComponent(resolve_path[-1],"object"))
+
+ try:
+ self._root_context.unbind(context_name)
+ except CosNaming.NamingContext.NotFound, ex:
+ return
+ except CORBA.Exception,ex:
+ return
+
+ def Destroy_FullDirectory(self,Path):
+ context_name=[]
+ for e in string.split(Path,'/'):
+ if e == '':continue
+ context_name.append(CosNaming.NameComponent(e,"dir"))
+
+ try:
+ context=self._root_context.resolve(context_name)
+ except CosNaming.NamingContext.NotFound, ex:
+ return
+ except CORBA.Exception,ex:
+ return
+
+ bl,bi=context.list(0)
+ if bi is not None:
+ ok,b=bi.next_one()
+ while(ok):
+ for s in b.binding_name :
+ if s.kind == "object":
+ context.unbind([s])
+ elif s.kind == "dir":
+ context.unbind([s])
+ ok,b=bi.next_one()
+
+ context.destroy()
+ self._root_context.unbind(context_name)
bp1->deleteInstance(bp1);
// --- trace on file
- char *theFileName = TRACEFILE;
+ const char *theFileName = TRACEFILE;
string s = "file:";
s += theFileName;
// --- Get or initialize the orb
int _argc = 1;
- char* _argv[] = {""};
+ char* _argv[] = {(char*)""};
ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance() ;
ASSERT(SINGLETON_<ORB_INIT>::IsAlreadyExisting());
_orb = init(_argc , _argv ) ;
map<int,client_infos *>::iterator im;
for (im=_reg.begin();im!=_reg.end(); im++)
{
+#if defined(_DEBUG_) || defined(_DEBUG)
const client_infos &lesInfos = *(*im).second ;
MESSAGE("Deletion") ; SCRUTE( lesInfos._name ) ;
+#endif
_reg.erase ( im ) ;
}
ASSERT(_reg.size()==0) ;
for (im=_fin.begin();im!=_fin.end(); im++)
{
+#if defined(_DEBUG_) || defined(_DEBUG)
const client_infos &lesInfos = *(*im).second ;
MESSAGE("Deletion") ; SCRUTE( lesInfos._name ) ;
+#endif
_fin.erase ( im ) ;
}
ASSERT(_fin.size()==0) ;
void SessionName( const char *sessionName ) ;
- void SetOrb( CORBA::ORB_ptr orb ) { _orb = orb; return; }
+ void SetOrb( CORBA::ORB_ptr orb ) { _orb = CORBA::ORB::_duplicate(orb); return; }
void Shutdown() { if(!CORBA::is_nil(_orb)) _orb->shutdown(0); }
ptrRegistry->SessionName( ptrSessionName ) ;
ptrRegistry->SetOrb(orb);
varComponents = ptrRegistry->_this() ;
+ ptrRegistry->_remove_ref(); //let poa manage registryservice deletion
// The RegistryService must not already exist.
try
PortableServer::ObjectId_var aStudyManager_iid = root_poa->activate_object(aStudyManager_i);
//give ownership to the poa : the object will be deleted by the poa
aStudyManager_i->_remove_ref();
- aStudyManager_i->register_name("/myStudyManager");
+ aStudyManager_i->register_name((char*)"/myStudyManager");
}
return new SALOMEDS_StudyManager();
}
std::string aValue;
if (_isLocal) {
SALOMEDS::Locker lock;
- char guid[40];
+ // char guid[40];
aValue = dynamic_cast<SALOMEDSImpl_AttributeUserID*>(_local_impl)->Value();
}
else aValue = SALOMEDS::AttributeUserID::_narrow(_corba_impl)->Value();
CORBA::LongLong addr = theGA->GetLocalImpl(GetHostname().c_str(), pid, _isLocal);
if(_isLocal) {
- _local_impl = ((SALOMEDSImpl_GenericAttribute*)(addr));
+ _local_impl = reinterpret_cast<SALOMEDSImpl_GenericAttribute*>(addr);
_corba_impl = SALOMEDS::GenericAttribute::_nil();
}
else {
return CORBA::string_dup(SALOMEDSImpl_GenericAttribute::Impl_GetType(_impl));
}
- return "";
+ return (char*)"";
}
char* SALOMEDS_GenericAttribute_i::GetClassType()
return CORBA::string_dup(SALOMEDSImpl_GenericAttribute::Impl_GetClassType(_impl));
}
- return "";
+ return (char*)"";
}
long pid = (long)getpid();
#endif
isLocal = (strcmp(theHostname, GetHostname().c_str()) == 0 && pid == thePID)?1:0;
- return ((CORBA::LongLong)_impl);
+ return reinterpret_cast<CORBA::LongLong>(_impl);
}
theSObject->GetLocalImpl(GetHostname().c_str(), pid, _isLocal);
if(_isLocal) {
- _local_impl = ((SALOMEDSImpl_SObject*)(addr));
+ _local_impl = reinterpret_cast<SALOMEDSImpl_SObject*>(addr);
_corba_impl = SALOMEDS::SObject::_duplicate(theSObject);
}
else {
long pid = (long)getpid();
#endif
isLocal = (strcmp(theHostname, GetHostname().c_str()) == 0 && pid == thePID)?1:0;
- return ((CORBA::LongLong)(void*)_impl);
+ return reinterpret_cast<CORBA::LongLong>(_impl);
}
long addr = theStudy->GetLocalImpl(GetHostname().c_str(), pid, _isLocal);
if(_isLocal) {
- _local_impl = ((SALOMEDSImpl_Study*)(addr));
+ _local_impl = reinterpret_cast<SALOMEDSImpl_Study*>(addr);
_corba_impl = SALOMEDS::Study::_duplicate(theStudy);
}
else {
CORBA::LongLong addr = theManager->GetLocalImpl(GetHostname().c_str(), pid, _isLocal);
if(_isLocal) {
- _local_impl = ((SALOMEDSImpl_StudyManager*)(addr));
+ _local_impl = reinterpret_cast<SALOMEDSImpl_StudyManager*>(addr);
_corba_impl = SALOMEDS::StudyManager::_duplicate(theManager);
}
else {
CORBA::LongLong addr = theManager->GetLocalImpl(GetHostname().c_str(), pid, _isLocal);
if(_isLocal) {
- _local_impl = ((SALOMEDSImpl_StudyManager*)(addr));
+ _local_impl = reinterpret_cast<SALOMEDSImpl_StudyManager*>(addr);
_corba_impl = SALOMEDS::StudyManager::_duplicate(theManager);
}
else {
* context name
*/
//============================================================================
-void SALOMEDS_StudyManager_i::register_name(char * name)
+void SALOMEDS_StudyManager_i::register_name(const char * name)
{
SALOMEDS::StudyManager_var aManager(_this());
_name_service->Register(aManager.in(), name);
long pid = (long)getpid();
#endif
isLocal = (strcmp(theHostname, GetHostname().c_str()) == 0 && pid == thePID)?1:0;
- return ((CORBA::LongLong)(void*)_impl);
+ return reinterpret_cast<CORBA::LongLong>(_impl);
}
//===========================================================================
/*!
\param char* arguments, the context to register the study manager in the NS
*/
- void register_name(char * name);
+ void register_name(const char * name);
//! method to Create a New Study of name study_name
/*!
long pid = (long)getpid();
#endif
isLocal = (strcmp(theHostname, GetHostname().c_str()) == 0 && pid == thePID)?1:0;
- return ((CORBA::LongLong)_impl);
+ return reinterpret_cast<CORBA::LongLong>(_impl);
}
void SALOMEDSTest::setUp()
{
int argc = 1;
- char* argv[] = {""};
+ char* argv[] = {(char*)""};
ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance() ;
ASSERT(SINGLETON_<ORB_INIT>::IsAlreadyExisting());
void SALOMEDSTest_Embedded::setUp()
{
int argc = 1;
- char* argv[] = {""};
+ char* argv[] = {(char*)""};
ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance() ;
ASSERT(SINGLETON_<ORB_INIT>::IsAlreadyExisting());
{
CheckLocked();
- SALOMEDSImpl_Study* aStudy = SALOMEDSImpl_Study::GetStudy(Label());
+ SALOMEDSImpl_Study::GetStudy(Label());
Backup();
myString = theValue;
if(aStr[0] == '0') //If the first character of the key is 0, then empty value
aValue = "";
else {
- long aSize = strtol(v[pos++].c_str(), NULL, 10);
+ strtol(v[pos++].c_str(), NULL, 10);
aValue = v[pos++];
}
myTable[aKey] = aValue;
sem_init(&_sem,0,0); // to wait until run thread is initialized
pthread_t traceThread;
int bid = 0;
- int re2 = pthread_create(&traceThread, NULL,
+ pthread_create(&traceThread, NULL,
FileTraceCollector::run, (void *)bid);
sem_wait(&_sem);
_singleton = myInstance; // _singleton known only when init done
//break;
}
- int fullBuf = myTraceBuffer->retrieve(myTrace);
+ myTraceBuffer->retrieve(myTrace);
if (myTrace.traceType == ABORT_MESS)
{
#ifndef WNT
DEVTRACE("New buffer pool");
LocalTraceBufferPool* myInstance = new LocalTraceBufferPool();
- DESTRUCTOR_OF<LocalTraceBufferPool> *ptrDestroy =
- new DESTRUCTOR_OF<LocalTraceBufferPool> (*myInstance);
+ new DESTRUCTOR_OF<LocalTraceBufferPool> (*myInstance);
_singleton = myInstance;
// --- start a trace Collector
}
else if (strncmp(traceKind,"file",strlen("file"))==0)
{
- char *fileName;
+ const char *fileName;
if (strlen(traceKind) > strlen("file"))
fileName = &traceKind[strlen("file")+1];
else
while (ret)
{
ret = sem_wait(&_fullBufferSemaphore);
- if (ret) perror(" LocalTraceBufferPool::retrieve, sem_wait");
+ if (ret) MESSAGE (" LocalTraceBufferPool::retrieve, sem_wait");
}
// get the next buffer to print
#include "SALOME_LocalTrace.hxx"
-#define TRACE_BUFFER_SIZE 256 // number of entries in circular buffer
+#define TRACE_BUFFER_SIZE 512 // number of entries in circular buffer
// must be power of 2
#define MAX_TRACE_LENGTH 1024 // messages are truncated at this size
sem_init(&_sem,0,0); // to wait until run thread is initialized
pthread_t traceThread;
- int re2 = pthread_create(&traceThread, NULL,
+ pthread_create(&traceThread, NULL,
LocalTraceCollector::run, NULL);
sem_wait(&_sem);
_singleton = myInstance; // _singleton known only when init done
//break;
}
- int fullBuf = myTraceBuffer->retrieve(myTrace);
+ myTraceBuffer->retrieve(myTrace);
if (myTrace.traceType == ABORT_MESS)
{
cout << flush ;
SALOMELocalTraceTest::testSingletonBufferPool()
{
// --- trace on file
- char *theFileName = TRACEFILE;
+ const char *theFileName = TRACEFILE;
string s = "file:";
s += theFileName;
for(t=0;t<numThread;t++)
{
- int ret = pthread_join(threads[t], NULL);
+ pthread_join(threads[t], NULL);
MESSAGE("--------------------- end of PrintHello thread " << t);
}
MESSAGE(" ---- end of PrintHello threads ---- ");
void
SALOMELocalTraceTest::testLoadBufferPoolFile()
{
- char *theFileName = TRACEFILE;
+ const char *theFileName = TRACEFILE;
string s = "file:";
s += theFileName;
for(t=0;t<NUM_THREADS;t++)
{
- int ret = pthread_join(threads[t], NULL);
+ pthread_join(threads[t], NULL);
MESSAGE("--------------------- end of PrintHello thread " << t);
}
MESSAGE(" ---- end of PrintHello threads ---- ");
void *PrintHello(void *threadid)
{
+#if defined(_DEBUG_) || defined(_DEBUG)
long id_thread = (long)threadid;
for (int i=0; i<NUM_MESSAGES;i++)
MESSAGE("Hello World! This is a trace test : " << id_thread
<< " - iter " << i);
+#endif
pthread_exit(NULL);
}
#define MESS_END std::endl; LocalTraceBufferPool::instance()->insert(NORMAL_MESS, os.str().c_str());
#define MESS_ABORT std::endl; LocalTraceBufferPool::instance()->insert(ABORT_MESS, os.str().c_str());
+// Macroses for messages with separated structure in c++ file in _DUBUG mode
+#define MESSAGE_BEGIN(msg) {std::ostringstream ss; ss <<__FILE__ <<" ["<<__LINE__<<"] : "<< msg; LocalTraceBufferPool::instance()->insert(NORMAL_MESS, ss.str().c_str());}
+#define MESSAGE_ADD(msg) {std::ostringstream ss; ss << msg; LocalTraceBufferPool::instance()->insert(NORMAL_MESS, ss.str().c_str());}
+#define MESSAGE_END(msg) {std::ostringstream ss; ss << msg << std::endl; LocalTraceBufferPool::instance()->insert(NORMAL_MESS, ss.str().c_str());}
+
// --- Some macros are always defined (without _DEBUG_): for use with release version
#define INFOS(msg) {MESS_BEGIN("- Trace ") << msg << MESS_END}
sem_init(&_sem,0,0); // to wait until run thread is initialized
pthread_t traceThread;
int bid = 0;
- int re2 = pthread_create(&traceThread, NULL,
+ pthread_create(&traceThread, NULL,
SALOMETraceCollector::run, (void *)bid);
sem_wait(&_sem);
_singleton = myInstance; // _singleton known only when init done
//break;
}
- int fullBuf = myTraceBuffer->retrieve(myTrace);
+ myTraceBuffer->retrieve(myTrace);
if (!CORBA::is_nil(_orb))
{
if (myTrace.traceType == ABORT_MESS)
for(t=0;t<NUM_THREADS;t++)
{
- int ret = pthread_join(threads[t], NULL);
+ pthread_join(threads[t], NULL);
MESSAGE("--------------------- end of PrintHello thread " << t);
}
MESSAGE(" ---- end of PrintHello threads ---- ");
void *PrintHello(void *threadid)
{
+#if defined(_DEBUG_) || defined(_DEBUG)
long id_thread = (long)threadid;
for (int i=0; i<NUM_MESSAGES;i++)
MESSAGE("Hello World! This is a trace test : " << id_thread
<< " - iter " << i);
+#endif
pthread_exit(NULL);
}
}
}
#ifndef WNT
- int a = nanosleep(&ts_req,&ts_rem);
+ nanosleep(&ts_req,&ts_rem);
#else
Sleep(TIMESleep / 1000000);
#endif
#ifndef _TRACECOLLECTOR_WAITFORSERVERREADINESS_HXX_
#define _TRACECOLLECTOR_WAITFORSERVERREADINESS_HXX_
+#include <SALOMEconfig.h>
#include <omniORB4/CORBA.h>
#include <string>
void Engines_TestComponent_i::Setenv()
{
- bool overwrite = true;
+ // bool overwrite = true;
map<std::string,CORBA::Any>::iterator it;
MESSAGE("set environment associated with keys in map _fieldsDict");
for (it = _fieldsDict.begin(); it != _fieldsDict.end(); it++)
s+='=';
s+=value;
//char* cast because 1st arg of linux putenv function is not a const char* !!!
- int ret=putenv((char *)s.c_str());
+ putenv((char *)s.c_str());
//End of CCRT porting
//int ret = setenv(cle.c_str(), value, overwrite);
MESSAGE("--- setenv: "<<cle<<" = "<< value);
Engines::TestComponent_ptr create_instance(Engines::Container_ptr iGenFact,
string componenttName)
{
+#if defined(_DEBUG_) || defined(_DEBUG)
bool isLib =
iGenFact->load_component_Library(componenttName.c_str());
// iGenFact->load_component_Library("SalomeTestComponent");
ASSERT(isLib);
+#else
+ iGenFact->load_component_Library(componenttName.c_str());
+#endif
CORBA::Object_var obj =
// iGenFact->create_component_instance("SalomeTestComponent",
iGenFact->create_component_instance(componenttName.c_str(),
bp1->deleteInstance(bp1);
// --- trace on file
- char *theFileName = TRACEFILE;
+ const char *theFileName = TRACEFILE;
string s = "file:";
s += theFileName;
# include "Utils_DESTRUCTEUR_GENERIQUE.hxx"
//# include "utilities.h"
+# include "LocalTraceBufferPool.hxx"
void Nettoyage();
#ifdef _DEBUG_
-static int MYDEBUG = 0;
+// static int MYDEBUG = 0;
#else
-static int MYDEBUG = 0;
+// static int MYDEBUG = 0;
#endif
using namespace std;
DESTRUCTEUR_GENERIQUE_::Destructeurs =
new std::list<DESTRUCTEUR_GENERIQUE_*> ; // Destructeur alloue dynamiquement (cf. ci-dessous) ,
// il est utilise puis detruit par la fonction Nettoyage
+ //To be sure the trace singleton will be the last one to be destroyed initialize it here before calling atexit
+ LocalTraceBufferPool::instance();
int cr = atexit( Nettoyage ); // execute Nettoyage lors de exit, aprs la destruction des donnees statiques !
assert(cr==0) ;
ATEXIT_Done = true ;
};
-# endif /* # if !defined( __SINGLETON__H__ ) */
+# endif /* # if !defined( __DESTRUCTEUR_GENERIQUE__H__ ) */
const struct utsname get_uname( void )
{
struct utsname hostid;
+#if defined(_DEBUG_) || defined(_DEBUG)
const int retour=uname(&hostid);
ASSERT(retour>=0);
+#else
+ uname(&hostid);
+#endif
return hostid ;
}
const char* get_adip( void )
{
struct utsname hostid;
+#if defined(_DEBUG_) || defined(_DEBUG)
const int retour=uname(&hostid);
ASSERT(retour>=0);
+#else
+ uname(&hostid);
+#endif
const hostent* pour_adip=gethostbyname(hostid.nodename);
ASSERT(pour_adip!=NULL);
# include <exception>
# include <iostream>
+#ifdef LOCALIZED
+#undef LOCALIZED
+#endif
#ifdef _DEBUG_
# define LOCALIZED(message) #message , __FILE__ , __LINE__
#else
}
void Utils_Timer::ShowAbsolute(){
+#if defined(_DEBUG_) || defined(_DEBUG)
#ifndef WNT
unsigned long Absolute_user = (unsigned long) ((timeval*)RefToCurrentTimeB)->tv_sec ;
#else
unsigned long Absolute_user = *RefToCurrentTimeB;
#endif
MESSAGE("Absolute time: " << Absolute_user << " seconds ");
+#endif
}