From 58e142d02a8a595201dd7db003c2e2b74f35b32c Mon Sep 17 00:00:00 2001 From: Viktor Uzlov Date: Thu, 29 Oct 2020 17:59:32 +0300 Subject: [PATCH] bos #20365 Problem with killSalomeWithPort --spy on Windows --- bin/killSalomeWithPort.py | 3 +- bin/runSalome.py | 4 +- bin/salome_utils.py | 1186 ++++++++++--------- bin/server.py | 286 ++--- src/NamingService/SALOME_NamingServicePy.py | 624 +++++----- 5 files changed, 1057 insertions(+), 1046 deletions(-) diff --git a/bin/killSalomeWithPort.py b/bin/killSalomeWithPort.py index 2ffbdd42a..d0af7b53e 100755 --- a/bin/killSalomeWithPort.py +++ b/bin/killSalomeWithPort.py @@ -381,11 +381,12 @@ def killMyPortSpy(pid, port): import omniORB orb = omniORB.CORBA.ORB_init(sys.argv, omniORB.CORBA.ORB_ID) import SALOME_NamingServicePy - ns = SALOME_NamingServicePy.SALOME_NamingServicePy_i(orb) + ns = SALOME_NamingServicePy.SALOME_NamingServicePy_i(orb, 3, True) import SALOME #@UnresolvedImport @UnusedImport session = ns.Resolve("/Kernel/Session") assert session except: + killMyPort(port) return try: status = session.GetStatSession() diff --git a/bin/runSalome.py b/bin/runSalome.py index 172298f98..93fa749e2 100755 --- a/bin/runSalome.py +++ b/bin/runSalome.py @@ -899,7 +899,7 @@ def foreGround(clt, args): server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(session_pid or os.getpid()), "%s"%(port)] else: server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(session_pid or os.getpid()), "%s"%(port)] - server.run() + server.run(True) # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port)) # -- dt = 1.0 @@ -944,6 +944,8 @@ def runSalome(): test = test and args['foreground'] # -- if test: + from time import sleep + sleep(3.0) foreGround(clt, args) pass pass diff --git a/bin/salome_utils.py b/bin/salome_utils.py index a80132894..ba151eef8 100644 --- a/bin/salome_utils.py +++ b/bin/salome_utils.py @@ -1,592 +1,594 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE -# -# 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, or (at your option) any later version. -# -# 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_utils.py -# Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com) -# --- - -## @package salome_utils -# \brief Set of utility functions used by SALOME python scripts. - -# -# Exported functions -# - -__all__ = [ - 'getORBcfgInfo', - 'getHostFromORBcfg', - 'getPortFromORBcfg', - 'getUserName', - 'getHostName', - 'getShortHostName', - 'getAppName', - 'getPortNumber', - 'getLogDir', - 'getTmpDir', - 'getHomeDir', - 'generateFileName', - 'makeTmpDir', - 'uniteFiles', - ] - -# --- - -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 does not represent a boolean, an exception is raised. - """ - if isinstance(arg, bool) : - return arg - elif isinstance(arg, (str, bytes)): - 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 (USERNAME on windows) - 2. if fails, try LOGNAME (un*x) - 3. if fails return 'unknown' as default user name - """ - import os, sys - if sys.platform == "win32": - return os.getenv("USERNAME", "unknown") - else: - user = os.getenv("USER") - if user: - return user - return os.getenv("LOGNAME", "unknown") -# --- - -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 - """ - 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 - try: - socket.gethostbyname(host) - except: - host = "localhost" - pass - 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(use_default=True): - """ - 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 (if use_default is True) or None (id use_default is False) - """ - import os - try: - return int( os.getenv( "NSPORT" ) ) - except: - pass - try: - port = int( getPortFromORBcfg() ) - if port is not None: return port - except: - pass - if use_default: return 2809 # '2809' is default port number - return None - -# --- - -def getHomeDir(): - """ - Get home directory. - """ - import os - return os.path.realpath(os.path.expanduser('~')) -# --- - -def getLogDir(): - """ - Get directory to be used for the log files. - """ - import os - return os.path.join(getTmpDir(), "logs", getUserName()) -# --- - -def getTmpDir(): - """ - Get directory to be used for the temporary files. - """ - import os, tempfile - f = tempfile.NamedTemporaryFile() - tmpdir = os.path.dirname(f.name) - f.close() - return tmpdir -# --- - -def generateFileName( dir, prefix = None, suffix = None, extension = None, - unique = False, separator = "_", hidden = False, **kwargs ): - """ - Generate file name by specified 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 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 - 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 os.path.normpath(name) - -# --- - -def makeTmpDir( path, mode=0o777 ): - """ - Make temporary directory with the specified path. - If the directory exists then clear its contents. - - Parameters: - - path : absolute path to the directory to be created. - - mode : access mode - """ - import os - if os.path.exists( path ): - import sys - if sys.platform == "win32": - os.system( "rmdir /S /Q " + '"' + path + '"' ) - os.system( "mkdir " + '"' + path + '"' ) - else: - os.system( "rm -rf " + path + "/*" ) - else: - dirs = path.split("/") - shift1 = shift2 = 0 - if not dirs[0]: shift1 = 1 - if dirs[-1]: shift2 = 1 - for i in range(1+shift1,len(dirs)+shift2): - p = "/".join(dirs[:i]) - try: - os.mkdir(p, mode) - os.chmod(p, mode) - except: - pass - -# --- - -def uniteFiles( src_file, dest_file ): - """ - Unite contents of the source file with contents of the destination file - and put result of the uniting to the destination file. - If the destination file does not exist then the source file is simply - copied to its path. - - Parameters: - - src_file : absolute path to the source file - - dest_file : absolute path to the destination file - """ - import os - - if not os.path.exists( src_file ): - return - pass - - if os.path.exists( dest_file ): - # add a symbol of new line to contents of the destination file (just in case) - dest = open( dest_file, 'r' ) - dest_lines = dest.readlines() - dest.close() - - dest_lines.append( "\n" ) - - dest = open( dest_file, 'w' ) - dest.writelines( dest_lines ) - dest.close() - - import sys - if sys.platform == "win32": - command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"' - else: - command = "cat " + src_file + " >> " + dest_file - pass - pass - else: - import sys - if sys.platform == "win32": - command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul" - else: - command = "cp " + src_file + " " + dest_file - pass - pass - - os.system( command ) - -# -- - -_verbose = None - -def verbose(): - """ - Get verbosity level. Default verbosity level is specified via the environment variable - SALOME_VERBOSE, e.g.: - [bash %] export SALOME_VERBOSE=1 - The function setVerbose() can be used to change verbosity level explicitly. - """ - global _verbose - # verbose has already been called - if _verbose is not None: - return _verbose - # first time - try: - from os import getenv - _verbose = int(getenv('SALOME_VERBOSE')) - except: - _verbose = 0 - pass - # - return _verbose -# -- - -def setVerbose(level): - """ - Change verbosity level. The function verbose() can be used to get current verbosity level. - """ - global _verbose - _verbose = level - return -# -- - -import signal -def killpid(pid, sig = 9): - """ - Send signal sig to the process by pid. - - Parameters: - - pid : PID of process - - sig : signal for sending - Possible values of signals: - 9 means kill the process - 0 only check existing of the process - NOTE: Other values are not processed on Windows - Returns: - 1 Success - 0 Fail, no such process - -1 Fail, another reason - - """ - if not pid: return - import os, sys - if sig != 0: - if verbose(): print("######## killpid pid = ", pid) - try: - if sys.platform == "win32": - import ctypes - if sig == 0: - # PROCESS_QUERY_INFORMATION (0x0400) Required to retrieve certain information about a process - handle = ctypes.windll.kernel32.OpenProcess(0x0400, False, int(pid)) - if handle: - ret = 1 - ctypes.windll.kernel32.CloseHandle(handle) - else: - ret = 0 - if sig == 9: - # PROCESS_TERMINATE (0x0001) Required to terminate a process using TerminateProcess. - handle = ctypes.windll.kernel32.OpenProcess(0x0001, False, int(pid)) - ret = ctypes.windll.kernel32.TerminateProcess(handle, -1) - ctypes.windll.kernel32.CloseHandle(handle) - pass - pass - else: - # Default: signal.SIGKILL = 9 - os.kill(int(pid),sig) - ret = 1 - pass - pass - except OSError as e: - # errno.ESRCH == 3 is 'No such process' - if e.errno == 3: - ret = 0 - else: - ret = -1 - pass - pass - return ret -# -- - -def getOmniNamesPid(port): - """ - Return OmniNames pid by port number. - """ - import sys,subprocess,re - if sys.platform == "win32": - # Get process list by WMI Command Line Utility(WMIC) - # Output is formatted with each value listed on a separate line and with the name of the property: - # ... - # Caption= - # CommandLine= - # ProcessId= - # - # - # - # Caption= - # CommandLine= - # ProcessId= - # ... - cmd = 'WMIC PROCESS get Caption,Commandline,Processid /VALUE' - proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) - # Get stdout - allProc = proc.communicate()[0].decode() - # find Pid of omniNames - pid = re.findall(r'Caption=.*omniNames.*\n?CommandLine=.*omniNames.*\D%s\D.*\n?ProcessId=(\d*)'%(port),allProc)[0] - else: - cmd = "ps -eo pid,command | grep -v grep | grep -E \"omniNames.*%s\" | awk '{print $1}'"%(port) - proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) - pid = proc.communicate()[0] - pass - - return pid -# -- - -def killOmniNames(port): - """ - Kill OmniNames process by port number. - """ - try: - pid = getOmniNamesPid(port) - if pid: killpid(pid) - except: - pass - pass -# -- +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE +# +# 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, or (at your option) any later version. +# +# 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_utils.py +# Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com) +# --- + +## @package salome_utils +# \brief Set of utility functions used by SALOME python scripts. + +# +# Exported functions +# + +__all__ = [ + 'getORBcfgInfo', + 'getHostFromORBcfg', + 'getPortFromORBcfg', + 'getUserName', + 'getHostName', + 'getShortHostName', + 'getAppName', + 'getPortNumber', + 'getLogDir', + 'getTmpDir', + 'getHomeDir', + 'generateFileName', + 'makeTmpDir', + 'uniteFiles', + ] + +# --- + +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 does not represent a boolean, an exception is raised. + """ + if isinstance(arg, bool) : + return arg + elif isinstance(arg, (str, bytes)): + 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 (USERNAME on windows) + 2. if fails, try LOGNAME (un*x) + 3. if fails return 'unknown' as default user name + """ + import os, sys + if sys.platform == "win32": + return os.getenv("USERNAME", "unknown") + else: + user = os.getenv("USER") + if user: + return user + return os.getenv("LOGNAME", "unknown") +# --- + +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 + """ + 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 + try: + socket.gethostbyname(host) + except: + host = "localhost" + pass + 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(use_default=True): + """ + 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 (if use_default is True) or None (id use_default is False) + """ + import os + try: + return int( os.getenv( "NSPORT" ) ) + except: + pass + try: + port = int( getPortFromORBcfg() ) + if port is not None: return port + except: + pass + if use_default: return 2809 # '2809' is default port number + return None + +# --- + +def getHomeDir(): + """ + Get home directory. + """ + import os + return os.path.realpath(os.path.expanduser('~')) +# --- + +def getLogDir(): + """ + Get directory to be used for the log files. + """ + import os + return os.path.join(getTmpDir(), "logs", getUserName()) +# --- + +def getTmpDir(): + """ + Get directory to be used for the temporary files. + """ + import os, tempfile + f = tempfile.NamedTemporaryFile() + tmpdir = os.path.dirname(f.name) + f.close() + return tmpdir +# --- + +def generateFileName( dir, prefix = None, suffix = None, extension = None, + unique = False, separator = "_", hidden = False, **kwargs ): + """ + Generate file name by specified 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 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 + 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 os.path.normpath(name) + +# --- + +def makeTmpDir( path, mode=0o777 ): + """ + Make temporary directory with the specified path. + If the directory exists then clear its contents. + + Parameters: + - path : absolute path to the directory to be created. + - mode : access mode + """ + import os + if os.path.exists( path ): + import sys + if sys.platform == "win32": + os.system( "rmdir /S /Q " + '"' + path + '"' ) + os.system( "mkdir " + '"' + path + '"' ) + else: + os.system( "rm -rf " + path + "/*" ) + else: + dirs = path.split("/") + shift1 = shift2 = 0 + if not dirs[0]: shift1 = 1 + if dirs[-1]: shift2 = 1 + for i in range(1+shift1,len(dirs)+shift2): + p = "/".join(dirs[:i]) + try: + os.mkdir(p, mode) + os.chmod(p, mode) + except: + pass + +# --- + +def uniteFiles( src_file, dest_file ): + """ + Unite contents of the source file with contents of the destination file + and put result of the uniting to the destination file. + If the destination file does not exist then the source file is simply + copied to its path. + + Parameters: + - src_file : absolute path to the source file + - dest_file : absolute path to the destination file + """ + import os + + if not os.path.exists( src_file ): + return + pass + + if os.path.exists( dest_file ): + # add a symbol of new line to contents of the destination file (just in case) + dest = open( dest_file, 'r' ) + dest_lines = dest.readlines() + dest.close() + + dest_lines.append( "\n" ) + + dest = open( dest_file, 'w' ) + dest.writelines( dest_lines ) + dest.close() + + import sys + if sys.platform == "win32": + command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"' + else: + command = "cat " + src_file + " >> " + dest_file + pass + pass + else: + import sys + if sys.platform == "win32": + command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul" + else: + command = "cp " + src_file + " " + dest_file + pass + pass + + os.system( command ) + +# -- + +_verbose = None + +def verbose(): + """ + Get verbosity level. Default verbosity level is specified via the environment variable + SALOME_VERBOSE, e.g.: + [bash %] export SALOME_VERBOSE=1 + The function setVerbose() can be used to change verbosity level explicitly. + """ + global _verbose + # verbose has already been called + if _verbose is not None: + return _verbose + # first time + try: + from os import getenv + _verbose = int(getenv('SALOME_VERBOSE')) + except: + _verbose = 0 + pass + # + return _verbose +# -- + +def setVerbose(level): + """ + Change verbosity level. The function verbose() can be used to get current verbosity level. + """ + global _verbose + _verbose = level + return +# -- + +import signal +def killpid(pid, sig = 9): + """ + Send signal sig to the process by pid. + + Parameters: + - pid : PID of process + - sig : signal for sending + Possible values of signals: + 9 means kill the process + 0 only check existing of the process + NOTE: Other values are not processed on Windows + Returns: + 1 Success + 0 Fail, no such process + -1 Fail, another reason + + """ + if not pid: return + import os, sys + if sig != 0: + if verbose(): print("######## killpid pid = ", pid) + try: + if sys.platform == "win32": + import ctypes + if sig == 0: + # PROCESS_QUERY_INFORMATION (0x0400) Required to retrieve certain information about a process + SYNCHRONIZE = 0x100000 + handle = ctypes.windll.kernel32.OpenProcess(SYNCHRONIZE, False, int(pid)) + waitObj = ctypes.windll.kernel32.WaitForSingleObject(handle, 0) + if waitObj: + ret = 1 + ctypes.windll.kernel32.CloseHandle(handle) + else: + ret = 0 + if sig == 9: + # PROCESS_TERMINATE (0x0001) Required to terminate a process using TerminateProcess. + handle = ctypes.windll.kernel32.OpenProcess(0x0001, False, int(pid)) + ret = ctypes.windll.kernel32.TerminateProcess(handle, -1) + ctypes.windll.kernel32.CloseHandle(handle) + pass + pass + else: + # Default: signal.SIGKILL = 9 + os.kill(int(pid),sig) + ret = 1 + pass + pass + except OSError as e: + # errno.ESRCH == 3 is 'No such process' + if e.errno == 3: + ret = 0 + else: + ret = -1 + pass + pass + return ret +# -- + +def getOmniNamesPid(port): + """ + Return OmniNames pid by port number. + """ + import sys,subprocess,re + if sys.platform == "win32": + # Get process list by WMI Command Line Utility(WMIC) + # Output is formatted with each value listed on a separate line and with the name of the property: + # ... + # Caption= + # CommandLine= + # ProcessId= + # + # + # + # Caption= + # CommandLine= + # ProcessId= + # ... + cmd = 'WMIC PROCESS get Caption,Commandline,Processid /VALUE' + proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) + # Get stdout + allProc = proc.communicate()[0].decode() + # find Pid of omniNames + pid = re.findall(r'Caption=.*omniNames.*\n?CommandLine=.*omniNames.*\D%s\D.*\n?ProcessId=(\d*)'%(port),allProc)[0] + else: + cmd = "ps -eo pid,command | grep -v grep | grep -E \"omniNames.*%s\" | awk '{print $1}'"%(port) + proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) + pid = proc.communicate()[0] + pass + + return pid +# -- + +def killOmniNames(port): + """ + Kill OmniNames process by port number. + """ + try: + pid = getOmniNamesPid(port) + if pid: killpid(pid) + except: + pass + pass +# -- diff --git a/bin/server.py b/bin/server.py index 855db1949..ac1ebcef2 100644 --- a/bin/server.py +++ b/bin/server.py @@ -1,141 +1,145 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE -# -# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, -# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS -# -# 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, or (at your option) any later version. -# -# 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 -# - -import os, sys, string -from salome_utils import getHostName -process_id = {} - -# ----------------------------------------------------------------------------- -# -# Definition des classes d'objets pour le lancement des Server CORBA -# - -class Server: - """Generic class for CORBA server launch""" - - server_launch_mode = "daemon" - - def initArgs(self): - self.PID=None - self.CMD=[] - self.ARGS=[] - if self.args.get('xterm'): - if sys.platform != "win32": - self.ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-hold'] - else: - self.ARGS=['cmd', '/c', 'start cmd.exe', '/K'] - - def __init__(self,args): - self.args=args - self.initArgs() - - @staticmethod - def set_server_launch_mode(mode): - if mode == "daemon" or mode == "fork": - Server.server_launch_mode = mode - else: - raise Exception("Unsupported server launch mode: %s" % mode) - - def run(self): - global process_id - myargs=self.ARGS - if self.args.get('xterm'): - # (Debian) send LD_LIBRARY_PATH to children shells (xterm) - if sys.platform == "darwin": - env_ld_library_path=['env', 'DYLD_LIBRARY_PATH=' - + os.getenv("DYLD_FALLBACK_LIBRARY_PATH")] - myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path - elif sys.platform != "win32": - env_ld_library_path=['env', 'LD_LIBRARY_PATH=' - + os.getenv("LD_LIBRARY_PATH")] - myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path - command = myargs + self.CMD - # print("command = ", command) - if sys.platform == "win32": - import subprocess - pid = subprocess.Popen(command).pid - elif Server.server_launch_mode == "fork": - pid = os.spawnvp(os.P_NOWAIT, command[0], command) - else: # Server launch mode is daemon - pid=self.daemonize(command) - if pid is not None: - #store process pid if it really exists - process_id[pid]=self.CMD - self.PID = pid - return pid - - def daemonize(self,args): - # to daemonize a process need to do the UNIX double-fork magic - # see Stevens, "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) - # and UNIX Programming FAQ 1.7 How do I get my program to act like a daemon? - # http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 - #open a pipe - c2pread, c2pwrite = os.pipe() - #do first fork - pid=os.fork() - if pid > 0: - #first parent - os.close(c2pwrite) - #receive real pid from child - data=os.read(c2pread,24) #read 24 bytes - os.waitpid(pid,0) #remove zombie - os.close(c2pread) - # return : first parent - childpid=int(data) - if childpid==-1: - return None - try: - os.kill(childpid,0) - return childpid - except: - return None - - #first child - # decouple from parent environment - os.setsid() - os.close(c2pread) - - # do second fork : second child not a session leader - try: - pid = os.fork() - if pid > 0: - #send real pid to parent - pid_str = "%d" % pid - os.write(c2pwrite,pid_str.encode()) - os.close(c2pwrite) - # exit from second parent - os._exit(0) - except OSError as e: - print("fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr) - os.write(c2pwrite,"-1") - os.close(c2pwrite) - sys.exit(1) - - #I am a daemon - os.close(0) #close stdin - os.open("/dev/null", os.O_RDWR) # redirect standard input (0) to /dev/null - try: - os.execvp(args[0], args) - except OSError as e: - print("(%s) launch failed: %d (%s)" % (args[0],e.errno, e.strerror), file=sys.stderr) - os._exit(127) +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE +# +# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, +# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS +# +# 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, or (at your option) any later version. +# +# 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 +# + +import os, sys, string +from salome_utils import getHostName +process_id = {} + +# ----------------------------------------------------------------------------- +# +# Definition des classes d'objets pour le lancement des Server CORBA +# + +class Server: + """Generic class for CORBA server launch""" + + server_launch_mode = "daemon" + + def initArgs(self): + self.PID=None + self.CMD=[] + self.ARGS=[] + if self.args.get('xterm'): + if sys.platform != "win32": + self.ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-hold'] + else: + self.ARGS=['cmd', '/c', 'start cmd.exe', '/K'] + + def __init__(self,args): + self.args=args + self.initArgs() + + @staticmethod + def set_server_launch_mode(mode): + if mode == "daemon" or mode == "fork": + Server.server_launch_mode = mode + else: + raise Exception("Unsupported server launch mode: %s" % mode) + + def run(self, daemon=False): + global process_id + myargs=self.ARGS + if self.args.get('xterm'): + # (Debian) send LD_LIBRARY_PATH to children shells (xterm) + if sys.platform == "darwin": + env_ld_library_path=['env', 'DYLD_LIBRARY_PATH=' + + os.getenv("DYLD_FALLBACK_LIBRARY_PATH")] + myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path + elif sys.platform != "win32": + env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + + os.getenv("LD_LIBRARY_PATH")] + myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path + command = myargs + self.CMD + # print("command = ", command) + if sys.platform == "win32": + import subprocess + if daemon: + DETACHED_PROCESS = 0x00000008 + pid = subprocess.Popen(command, creationflags=DETACHED_PROCESS).pid + else: + pid = subprocess.Popen(command).pid + elif Server.server_launch_mode == "fork": + pid = os.spawnvp(os.P_NOWAIT, command[0], command) + else: # Server launch mode is daemon + pid=self.daemonize(command) + if pid is not None: + #store process pid if it really exists + process_id[pid]=self.CMD + self.PID = pid + return pid + + def daemonize(self,args): + # to daemonize a process need to do the UNIX double-fork magic + # see Stevens, "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) + # and UNIX Programming FAQ 1.7 How do I get my program to act like a daemon? + # http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 + #open a pipe + c2pread, c2pwrite = os.pipe() + #do first fork + pid=os.fork() + if pid > 0: + #first parent + os.close(c2pwrite) + #receive real pid from child + data=os.read(c2pread,24) #read 24 bytes + os.waitpid(pid,0) #remove zombie + os.close(c2pread) + # return : first parent + childpid=int(data) + if childpid==-1: + return None + try: + os.kill(childpid,0) + return childpid + except: + return None + + #first child + # decouple from parent environment + os.setsid() + os.close(c2pread) + + # do second fork : second child not a session leader + try: + pid = os.fork() + if pid > 0: + #send real pid to parent + pid_str = "%d" % pid + os.write(c2pwrite,pid_str.encode()) + os.close(c2pwrite) + # exit from second parent + os._exit(0) + except OSError as e: + print("fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr) + os.write(c2pwrite,"-1") + os.close(c2pwrite) + sys.exit(1) + + #I am a daemon + os.close(0) #close stdin + os.open("/dev/null", os.O_RDWR) # redirect standard input (0) to /dev/null + try: + os.execvp(args[0], args) + except OSError as e: + print("(%s) launch failed: %d (%s)" % (args[0],e.errno, e.strerror), file=sys.stderr) + os._exit(127) diff --git a/src/NamingService/SALOME_NamingServicePy.py b/src/NamingService/SALOME_NamingServicePy.py index 9b5b06db1..7228423df 100644 --- a/src/NamingService/SALOME_NamingServicePy.py +++ b/src/NamingService/SALOME_NamingServicePy.py @@ -1,311 +1,313 @@ -#! /usr/bin/env python3 -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE -# -# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, -# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS -# -# 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, or (at your option) any later version. -# -# 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 -# - -# SALOME NamingService : wrapping NamingService services -# File : SALOME_NamingServicePy.py -# Author : Estelle Deville, CEA -# Module : SALOME -# $Header$ -## @package SALOME_NamingServicePy -# \brief Module to manage SALOME naming service from python -# -import sys -import time -from omniORB import CORBA -import CosNaming -import string -from string import * - -from SALOME_utilities import * -#============================================================================= - -class SALOME_NamingServicePy_i(object): - """ - A class to manage SALOME naming service from python code - """ - _orb = None - _root_context=None - _current_context=None - _obj=None - - #------------------------------------------------------------------------- - - def __init__(self, orb=None): - """ - Standard Constructor, with ORB reference. - - Initializes the naming service root context - """ - #MESSAGE ( "SALOME_NamingServicePy_i::__init__" ) - if orb is None: - orb=CORBA.ORB_init([''], CORBA.ORB_ID) - self._orb = orb - # initialize root context and current context - ok = 0 - steps = 240 - while steps > 0 and ok == 0: - try: - obj =self._orb.resolve_initial_references("NameService") - self._root_context =obj._narrow(CosNaming.NamingContext) - self._current_context = self._root_context - - - if self._root_context is None : - #MESSAGE ( "Name Service Reference is invalid" ) - #sys.exit(1) - MESSAGE(" Name service not found") - else: - ok = 1 - except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE): - MESSAGE(" Name service not found") - time.sleep(0.25) - steps = steps - 1 - if steps == 0 and self._root_context is None: - MESSAGE ( "Name Service Reference is invalid" ) - sys.exit(1) - - #------------------------------------------------------------------------- - - def Register(self,ObjRef, Path): - """ ns.Register(object,pathname ) - - register a CORBA object under a pathname - """ - - MESSAGE ( "SALOME_NamingServicePy_i::Register" ) - _not_exist = 0 - path_list = list(Path) - if path_list[0]=='/': - self._current_context = self._root_context - #delete first '/' before split - Path=Path[1:] - - result_resolve_path = Path.split('/') - 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 - # is already done - # If not, the new context has to be created - _context_name = [] - for i in range(len(result_resolve_path)-1): - _context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir")) - - try: - obj = self._current_context.resolve(_context_name) - self._current_context = obj._narrow(CosNaming.NamingContext) - except CosNaming.NamingContext.NotFound as ex: - _not_exist = 1 - except CosNaming.NamingContext.InvalidName as ex: - MESSAGE ( "Register : CosNaming.NamingContext.InvalidName" ) - except CosNaming.NamingContext.CannotProceed as ex: - MESSAGE ( "Register : CosNaming.NamingContext.CannotProceed" ) - except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE): - MESSAGE ( "Register : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" ) - - if _not_exist: - # at least one context of the complete path is not created, we had - # to create it or them - _context_name = [] - for i in range(len(result_resolve_path)-1): - _context_name = [CosNaming.NameComponent(result_resolve_path[i],"dir")] - - try: - obj = self._current_context.resolve(_context_name) - self._current_context = obj._narrow(CosNaming.NamingContext) - except CosNaming.NamingContext.NotFound as ex: - #This context is not created. It will be done - self._current_context = self._current_context.bind_new_context(_context_name) - - #The current directory is now the directory where the object should - #be recorded - - _context_name = [CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"object")] - try: - self._current_context.bind(_context_name,ObjRef) - except CosNaming.NamingContext.NotFound as ex: - MESSAGE ( "Register : CosNaming.NamingContext.NotFound" ) - except CosNaming.NamingContext.InvalidName as ex: - MESSAGE ( "Register : CosNaming.NamingContext.InvalidName" ) - except CosNaming.NamingContext.CannotProceed as ex: - MESSAGE ( "Register : CosNaming.NamingContext.CannotProceed" ) - except CosNaming.NamingContext.AlreadyBound as ex: - MESSAGE ( "Register : CosNaming.NamingContext.AlreadyBound, object will be rebind" ) - self._current_context.rebind(_context_name,ObjRef) - except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE): - MESSAGE ( "Register : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" ) - - #------------------------------------------------------------------------- - - def Resolve(self, Path): - """ ns.Resolve(pathname) -> object - - find a CORBA object (ior) by its pathname - """ - #MESSAGE ( "SALOME_NamingServicePy_i::Resolve" ) - path_list = list(Path) - if path_list[0]=='/': - self._current_context = self._root_context - #delete first '/' before split - Path=Path[1:] - - result_resolve_path = Path.split('/') - _context_name=[] - for i in range(len(result_resolve_path)-1): - _context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir")) - _context_name.append(CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"object")) - try: - self._obj = self._current_context.resolve(_context_name) - except CosNaming.NamingContext.NotFound as ex: - MESSAGE ( "Resolve : CosNaming.NamingContext.NotFound" ) - self._obj = None - except CosNaming.NamingContext.InvalidName as ex: - MESSAGE ( "Resolve : CosNaming.NamingContext.InvalidName" ) - self._obj = None - except CosNaming.NamingContext.CannotProceed as ex: - MESSAGE ( "Resolve : CosNaming.NamingContext.CannotProceed" ) - self._obj = None - except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE): - MESSAGE ( "Resolve : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" ) - self._obj = None - return self._obj - - #------------------------------------------------------------------------- - - def Resolve_Dir(self, Path): - """ ns.Resolve_Dir(pathname) -> dir - - find a CORBA object (ior) by its pathname - """ - #MESSAGE ( "SALOME_NamingServicePy_i::Resolve" ) - path_list = list(Path) - if path_list[0]=='/': - self._current_context = self._root_context - #delete first '/' before split - Path=Path[1:] - - result_resolve_path = Path.split('/') - _context_name=[] - for i in range(len(result_resolve_path)-1): - _context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir")) - _context_name.append(CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"dir")) - print(_context_name) - return None - try: - self._obj = self._current_context.resolve(_context_name) - except CosNaming.NamingContext.NotFound as ex: - MESSAGE ( "Resolve : CosNaming.NamingContext.NotFound" ) - self._obj = None - except CosNaming.NamingContext.InvalidName as ex: - MESSAGE ( "Resolve : CosNaming.NamingContext.InvalidName" ) - self._obj = None - except CosNaming.NamingContext.CannotProceed as ex: - MESSAGE ( "Resolve : CosNaming.NamingContext.CannotProceed" ) - self._obj = None - except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE): - MESSAGE ( "Resolve : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" ) - self._obj = None - return self._obj - - - #------------------------------------------------------------------------- - - def Create_Directory(self,ObjRef, Path): - """ ns.Create_Directory(ObjRef, Path) - - create a sub directory - """ - MESSAGE ( "SALOME_NamingServicePy_i::Create_Directory" ) - _not_exist = 0 - path_list = list(Path) - if path_list[0]=='/': - self._current_context = self._root_context - #delete first '/' before split - Path=Path[1:] - - result_resolve_path = Path.split('/') - _context_name = [] - for i in range(len(result_resolve_path)): - _context_name[CosNaming.NameComponent(result_resolve_path[i],"dir")] - try: - obj = self._current_context.resolve(_context_name) - self._current_context = obj._narrow(CosNaming.NamingContext) - except CosNaming.NamingContext.NotFound as ex: - self._current_context = self._current_context.bind_new_context(_context_name) - except CosNaming.NamingContext.InvalidName as ex: - MESSAGE ( "Create_Directory : CosNaming.NamingContext.InvalidName" ) - except CosNaming.NamingContext.CannotProceed as ex: - 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): - """ ns.Destroy_Name(Path) - - remove a name in naming service - """ - resolve_path=Path.split('/') - 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 as ex: - return - except CORBA.Exception as ex: - return - - def Destroy_FullDirectory(self,Path): - """ ns.Destroy_FullDirectory(Path) - - remove recursively a directory - """ - context_name=[] - for e in Path.split('/'): - if e == '':continue - context_name.append(CosNaming.NameComponent(e,"dir")) - - try: - context=self._root_context.resolve(context_name) - except CosNaming.NamingContext.NotFound as ex: - return - except CORBA.Exception as 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) +#! /usr/bin/env python3 +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE +# +# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, +# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS +# +# 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, or (at your option) any later version. +# +# 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 +# + +# SALOME NamingService : wrapping NamingService services +# File : SALOME_NamingServicePy.py +# Author : Estelle Deville, CEA +# Module : SALOME +# $Header$ +## @package SALOME_NamingServicePy +# \brief Module to manage SALOME naming service from python +# +import sys +import time +from omniORB import CORBA +import CosNaming +import string +from string import * + +from SALOME_utilities import * +#============================================================================= + +class SALOME_NamingServicePy_i(object): + """ + A class to manage SALOME naming service from python code + """ + _orb = None + _root_context=None + _current_context=None + _obj=None + + #------------------------------------------------------------------------- + + def __init__(self, orb=None, steps=240, spy=False): + """ + Standard Constructor, with ORB reference. + + Initializes the naming service root context + """ + #MESSAGE ( "SALOME_NamingServicePy_i::__init__" ) + if orb is None: + orb=CORBA.ORB_init([''], CORBA.ORB_ID) + self._orb = orb + # initialize root context and current context + ok = 0 + while steps > 0 and ok == 0: + try: + obj =self._orb.resolve_initial_references("NameService") + self._root_context =obj._narrow(CosNaming.NamingContext) + self._current_context = self._root_context + + + if self._root_context is None : + #MESSAGE ( "Name Service Reference is invalid" ) + #sys.exit(1) + MESSAGE(" Name service not found") + else: + ok = 1 + except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE): + MESSAGE(" Name service not found") + time.sleep(0.25) + steps = steps - 1 + if steps == 0 and self._root_context is None: + MESSAGE ( "Name Service Reference is invalid" ) + if spy: + raise ValueError("Name Service Reference is invalid") + else: + sys.exit(1) + + #------------------------------------------------------------------------- + + def Register(self,ObjRef, Path): + """ ns.Register(object,pathname ) + + register a CORBA object under a pathname + """ + + MESSAGE ( "SALOME_NamingServicePy_i::Register" ) + _not_exist = 0 + path_list = list(Path) + if path_list[0]=='/': + self._current_context = self._root_context + #delete first '/' before split + Path=Path[1:] + + result_resolve_path = Path.split('/') + 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 + # is already done + # If not, the new context has to be created + _context_name = [] + for i in range(len(result_resolve_path)-1): + _context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir")) + + try: + obj = self._current_context.resolve(_context_name) + self._current_context = obj._narrow(CosNaming.NamingContext) + except CosNaming.NamingContext.NotFound as ex: + _not_exist = 1 + except CosNaming.NamingContext.InvalidName as ex: + MESSAGE ( "Register : CosNaming.NamingContext.InvalidName" ) + except CosNaming.NamingContext.CannotProceed as ex: + MESSAGE ( "Register : CosNaming.NamingContext.CannotProceed" ) + except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE): + MESSAGE ( "Register : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" ) + + if _not_exist: + # at least one context of the complete path is not created, we had + # to create it or them + _context_name = [] + for i in range(len(result_resolve_path)-1): + _context_name = [CosNaming.NameComponent(result_resolve_path[i],"dir")] + + try: + obj = self._current_context.resolve(_context_name) + self._current_context = obj._narrow(CosNaming.NamingContext) + except CosNaming.NamingContext.NotFound as ex: + #This context is not created. It will be done + self._current_context = self._current_context.bind_new_context(_context_name) + + #The current directory is now the directory where the object should + #be recorded + + _context_name = [CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"object")] + try: + self._current_context.bind(_context_name,ObjRef) + except CosNaming.NamingContext.NotFound as ex: + MESSAGE ( "Register : CosNaming.NamingContext.NotFound" ) + except CosNaming.NamingContext.InvalidName as ex: + MESSAGE ( "Register : CosNaming.NamingContext.InvalidName" ) + except CosNaming.NamingContext.CannotProceed as ex: + MESSAGE ( "Register : CosNaming.NamingContext.CannotProceed" ) + except CosNaming.NamingContext.AlreadyBound as ex: + MESSAGE ( "Register : CosNaming.NamingContext.AlreadyBound, object will be rebind" ) + self._current_context.rebind(_context_name,ObjRef) + except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE): + MESSAGE ( "Register : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" ) + + #------------------------------------------------------------------------- + + def Resolve(self, Path): + """ ns.Resolve(pathname) -> object + + find a CORBA object (ior) by its pathname + """ + #MESSAGE ( "SALOME_NamingServicePy_i::Resolve" ) + path_list = list(Path) + if path_list[0]=='/': + self._current_context = self._root_context + #delete first '/' before split + Path=Path[1:] + + result_resolve_path = Path.split('/') + _context_name=[] + for i in range(len(result_resolve_path)-1): + _context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir")) + _context_name.append(CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"object")) + try: + self._obj = self._current_context.resolve(_context_name) + except CosNaming.NamingContext.NotFound as ex: + MESSAGE ( "Resolve : CosNaming.NamingContext.NotFound" ) + self._obj = None + except CosNaming.NamingContext.InvalidName as ex: + MESSAGE ( "Resolve : CosNaming.NamingContext.InvalidName" ) + self._obj = None + except CosNaming.NamingContext.CannotProceed as ex: + MESSAGE ( "Resolve : CosNaming.NamingContext.CannotProceed" ) + self._obj = None + except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE): + MESSAGE ( "Resolve : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" ) + self._obj = None + return self._obj + + #------------------------------------------------------------------------- + + def Resolve_Dir(self, Path): + """ ns.Resolve_Dir(pathname) -> dir + + find a CORBA object (ior) by its pathname + """ + #MESSAGE ( "SALOME_NamingServicePy_i::Resolve" ) + path_list = list(Path) + if path_list[0]=='/': + self._current_context = self._root_context + #delete first '/' before split + Path=Path[1:] + + result_resolve_path = Path.split('/') + _context_name=[] + for i in range(len(result_resolve_path)-1): + _context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir")) + _context_name.append(CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"dir")) + print(_context_name) + return None + try: + self._obj = self._current_context.resolve(_context_name) + except CosNaming.NamingContext.NotFound as ex: + MESSAGE ( "Resolve : CosNaming.NamingContext.NotFound" ) + self._obj = None + except CosNaming.NamingContext.InvalidName as ex: + MESSAGE ( "Resolve : CosNaming.NamingContext.InvalidName" ) + self._obj = None + except CosNaming.NamingContext.CannotProceed as ex: + MESSAGE ( "Resolve : CosNaming.NamingContext.CannotProceed" ) + self._obj = None + except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE): + MESSAGE ( "Resolve : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" ) + self._obj = None + return self._obj + + + #------------------------------------------------------------------------- + + def Create_Directory(self,ObjRef, Path): + """ ns.Create_Directory(ObjRef, Path) + + create a sub directory + """ + MESSAGE ( "SALOME_NamingServicePy_i::Create_Directory" ) + _not_exist = 0 + path_list = list(Path) + if path_list[0]=='/': + self._current_context = self._root_context + #delete first '/' before split + Path=Path[1:] + + result_resolve_path = Path.split('/') + _context_name = [] + for i in range(len(result_resolve_path)): + _context_name[CosNaming.NameComponent(result_resolve_path[i],"dir")] + try: + obj = self._current_context.resolve(_context_name) + self._current_context = obj._narrow(CosNaming.NamingContext) + except CosNaming.NamingContext.NotFound as ex: + self._current_context = self._current_context.bind_new_context(_context_name) + except CosNaming.NamingContext.InvalidName as ex: + MESSAGE ( "Create_Directory : CosNaming.NamingContext.InvalidName" ) + except CosNaming.NamingContext.CannotProceed as ex: + 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): + """ ns.Destroy_Name(Path) + + remove a name in naming service + """ + resolve_path=Path.split('/') + 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 as ex: + return + except CORBA.Exception as ex: + return + + def Destroy_FullDirectory(self,Path): + """ ns.Destroy_FullDirectory(Path) + + remove recursively a directory + """ + context_name=[] + for e in Path.split('/'): + if e == '':continue + context_name.append(CosNaming.NameComponent(e,"dir")) + + try: + context=self._root_context.resolve(context_name) + except CosNaming.NamingContext.NotFound as ex: + return + except CORBA.Exception as 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) -- 2.39.2