From 2b71c6b27a5fc06364afa97937f9ff665168d082 Mon Sep 17 00:00:00 2001 From: vsr Date: Mon, 7 Jul 2008 07:55:49 +0000 Subject: [PATCH] * Issue 0019872: use dot-prefixed pidict files * Improve other SALOME scripts --- bin/NSparam.py | 27 +----- bin/addToKillList.py | 94 +++++++++--------- bin/envSalome.py | 2 +- bin/killSalome.py | 40 ++++---- bin/killSalomeWithPort.py | 170 ++++++++++++++++++++------------- bin/runSalome.py | 178 +++++++++++++++++----------------- bin/salome_session.py | 49 ++++++---- bin/salome_utilities.py | 196 ++++++++++++++++++++++++++------------ bin/setenv.py | 28 +++--- 9 files changed, 444 insertions(+), 340 deletions(-) diff --git a/bin/NSparam.py b/bin/NSparam.py index 652e6da66..2f93c9e54 100755 --- a/bin/NSparam.py +++ b/bin/NSparam.py @@ -20,7 +20,6 @@ # import sys,os -import string def getNSparams(info=""): """ @@ -32,25 +31,8 @@ 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 @@ -80,9 +62,10 @@ if __name__ == "__main__": getNSparams('port') pass else: - getNSparams('') + getNSparams() pass pass else: - getNSparams('') + getNSparams() pass + pass diff --git a/bin/addToKillList.py b/bin/addToKillList.py index 537dfaf3d..c1d4b91c9 100755 --- a/bin/addToKillList.py +++ b/bin/addToKillList.py @@ -25,78 +25,82 @@ from launchConfigureParser import verbose ########## 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(command) + command=command.split()[0] try: - process_ids.append({command_pid: [command]}) + if verbose(): print "addToKillList: %s : %s" % ( str(command_pid), command ) + process_ids.append({int(command_pid): [command]}) 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 to the kill list" % filedict 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() + filedict=getPiDict(port) 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: @@ -106,11 +110,11 @@ def killList(): 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 diff --git a/bin/envSalome.py b/bin/envSalome.py index 1d0d61cb6..ed153d41b 100755 --- a/bin/envSalome.py +++ b/bin/envSalome.py @@ -39,6 +39,6 @@ sys.argv = argv[1:] #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) diff --git a/bin/killSalome.py b/bin/killSalome.py index 2f1388182..69e083113 100755 --- a/bin/killSalome.py +++ b/bin/killSalome.py @@ -19,36 +19,40 @@ # 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) + # new-style dot-prefixed pidict file + fnamere = re.compile("^%s$"%(getPiDict('(\d*)',full=False,hidden=True))) + # provide compatibility with old-style pidict file (not dot-prefixed) + fnamere1 = re.compile("^%s$"%(getPiDict('(\d*)',full=False,hidden=False))) for file in os.listdir(os.getenv("HOME")): - mo = re.match(fnamere,file) + mo = fnamere.match(file) + if not mo: mo = fnamere1.match(file) if mo and len(mo.groups()): - killMyPort(mo.groups()[0]) + killMyPort(mo.group(1)) 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: + 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 diff --git a/bin/killSalomeWithPort.py b/bin/killSalomeWithPort.py index 79c168279..d4f7a37e2 100755 --- a/bin/killSalomeWithPort.py +++ b/bin/killSalomeWithPort.py @@ -22,47 +22,58 @@ 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 .___SALOME_pidict + where + is user name + is host name + is port number - filedict = '_'.join(filedict) - if full: - filedict = os.getenv("HOME") + '/' + filedict - return 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 + dir = "" + if full: dir = os.getenv("HOME") + 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] != '/': @@ -75,77 +86,100 @@ def appliCleanOmniOrbConfig(port): 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 diff --git a/bin/runSalome.py b/bin/runSalome.py index 7d9db1f15..2a8aa66b1 100755 --- a/bin/runSalome.py +++ b/bin/runSalome.py @@ -19,7 +19,7 @@ # 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 * @@ -209,17 +209,17 @@ class LoggerServer(Server): else: dirpath = "/tmp" logfile = generateFileName( dirpath, prefix="logger", - extension=".log", + extension="log", with_username=True, with_hostname=True, with_port=True) - if verbose(): - print "===========================================================" - print "Logger server: put log to the file:" - print logfile - print "===========================================================" - pass + print "===========================================================" + print "Logger server: put log to the file:" + print logfile + print "===========================================================" self.CMD=['SALOME_Logger_Server', logfile] + pass + pass # end of LoggerServer class # --- @@ -633,22 +633,14 @@ def useSalome(args, modules_list, modules_root_dir): #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): @@ -724,89 +716,89 @@ def registerEnv(args, modules_list, modules_root_dir): 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: + os.remove(last_running_config) + os.symlink(omniorb_config, last_running_config) + pass + pass + except: + pass break print "%s"%(NSPORT), if NSPORT == limit: @@ -836,14 +828,16 @@ def no_main(): 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 diff --git a/bin/salome_session.py b/bin/salome_session.py index 870b53bc4..64e13c951 100644 --- a/bin/salome_session.py +++ b/bin/salome_session.py @@ -39,48 +39,55 @@ def getShortHostName(): 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 diff --git a/bin/salome_utilities.py b/bin/salome_utilities.py index 7a2726a25..d5d3a677b 100644 --- a/bin/salome_utilities.py +++ b/bin/salome_utilities.py @@ -2,20 +2,20 @@ # 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 +# 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 +# +# 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 +# +# 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 @@ -33,9 +33,13 @@ Set of utility functions used by SALOME python scripts. __all__ = [ 'getUserName', 'getHostName', + 'getShortHostName', 'getAppName', 'getPortNumber', - 'generateFileName' + 'generateFileName', + 'getORBcfgInfo', + 'getHostFromORBcfg', + 'getPortFromORBcfg', ] # --- @@ -59,6 +63,61 @@ def _try_bool( arg ): # --- +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: @@ -81,9 +140,10 @@ def getHostName(): import os try: import socket - host = socket.gethostname().split('.')[0] + 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 @@ -91,6 +151,22 @@ def getHostName(): # --- +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: @@ -114,52 +190,45 @@ def getPortNumber(): return int( os.getenv( "NSPORT" ) ) except: pass - try: - f = open( os.getenv( "OMNIORB_CONFIG" ) ) - lines = f.readlines() - f.close() - regvar = re.compile( "(ORB)?InitRef.*:(\d+)\s*$" ) - for l in lines: - try: - return regvar.match( l ).group( 2 ) - except: - pass - pass - pass - except: - pass + port = getPortFromORBcfg() + if port is not None: return port return 2809 # '2809' is default port number # --- -def generateFileName( dir, prefix, suffix = None, extension = None, - unique = False, separator = "_", **kwargs ): - """ - Generate unique file name. - - The following parameters are supported: - - directory for the tmp file - - file prefix - - file suffix (not added by default) - - file extension (not added by default) - - separator of the words ('_' by default) - 'add user name' flag/option: - - boolean value can be passed to determine user name automatically - - string value to be used as user name - 'add host name' flag/option: - - boolean value can be passed to determine host name automatically - - string value to be used as host name - 'add port number' flag/option: - - boolean value can be passed to determine port number automatically - - string value to be used as port number - 'add application name' flag/option: - - boolean value can be passed to determine application name automatically - - string value to be used as application name - All parameters are optional. - If this parameter is True the unique file name is generated: +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 directory, an integer suffix is added to the end of + in the 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 parameters are optional. """ supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ] from launchConfigureParser import verbose @@ -172,7 +241,7 @@ def generateFileName( dir, prefix, suffix = None, extension = None, separator = str( separator ) pass # prefix (if specified) - if prefix: + if prefix is not None: filename.append( str( prefix ) ) pass # additional keywords @@ -200,7 +269,7 @@ def generateFileName( dir, prefix, suffix = None, extension = None, elif kw == 'with_hostname': try: # auto host name ? - if _try_bool( kwargs[kw] ): filename.append( getHostName() ) + if _try_bool( kwargs[kw] ): filename.append( getShortHostName() ) pass except: # host name given as parameter @@ -231,22 +300,29 @@ def generateFileName( dir, prefix, suffix = None, extension = None, pass pass # suffix (if specified) - if suffix: + if suffix is not None: filename.append( str( suffix ) ) pass # raise an exception if file name is empty if not filename: raise "Empty file name" - # create unique file name + # + if extension is not None and extension.startswith("."): extension = extension[1:] + # import os - name = os.path.join( dir, separator.join( filename ) ) - if extension: name += str( extension ) + 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 = os.path.join( dir, separator.join( filename ) + separator + str( index ) ) - if extension: name += str( extension ) + 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 diff --git a/bin/setenv.py b/bin/setenv.py index 86a4803ba..4d06f3885 100755 --- a/bin/setenv.py +++ b/bin/setenv.py @@ -75,7 +75,7 @@ def get_lib_dir(): # ----------------------------------------------------------------------------- -def get_config(): +def get_config(silent=False): """ Get list of modules, paths. @@ -116,12 +116,14 @@ def get_config(): 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 @@ -147,7 +149,7 @@ def get_config(): # ----------------------------------------------------------------------------- -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] @@ -261,7 +263,7 @@ def set_env(args, modules_list, modules_root_dir): 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 @@ -273,16 +275,16 @@ def set_env(args, modules_list, modules_root_dir): 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 # ----------------------------------------------------------------------------- -- 2.39.2