Salome HOME
Fix return statement for 'salome context'
[modules/kernel.git] / bin / salome_utils.py
index 95e87f42cfdbc871f708f0014f1320c4abf10384..4f4936f97cf96b99315d7783f9959ebe43a35fc5 100644 (file)
@@ -1,10 +1,10 @@
 #  -*- coding: iso-8859-1 -*-
 #  -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
+# Copyright (C) 2007-2016  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
 #
 # 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.
+# 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
 #
 # This library is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -39,6 +39,7 @@ __all__ = [
     'getShortHostName',
     'getAppName',
     'getPortNumber',
     'getShortHostName',
     'getAppName',
     'getPortNumber',
+    'getLogDir',
     'getTmpDir',
     'getHomeDir',
     'generateFileName',
     'getTmpDir',
     'getHomeDir',
     'generateFileName',
@@ -71,7 +72,7 @@ def getORBcfgInfo():
     """
     Get omniORB current configuration.
     Returns a list of three values: [ orb_version, host_name, port_number ].
     """
     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
     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
@@ -125,12 +126,18 @@ def getPortFromORBcfg():
 def getUserName():
     """
     Get user name:
 def getUserName():
     """
     Get user name:
-    1. try USER environment variable
-    2. if fails, return 'unknown' as default 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
-    return os.getenv( "USER", "unknown" ) # 'unknown' is 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():
 # ---
 
 def getHostName():
@@ -141,7 +148,6 @@ def getHostName():
     3. if fails, try HOST environment variable
     4. if fails, return 'unknown' as default host name
     """
     3. if fails, try HOST environment variable
     4. if fails, return 'unknown' as default host name
     """
-    import os
     try:
         import socket
         host = socket.gethostname()
     try:
         import socket
         host = socket.gethostname()
@@ -151,6 +157,11 @@ def getHostName():
     if not host: host = os.getenv("HOSTNAME")
     if not host: host = os.getenv("HOST")
     if not host: host = "unknown"           # 'unknown' is default host name
     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
 
 # ---
     return host
 
 # ---
@@ -168,7 +179,7 @@ def getShortHostName():
     except:
         pass
     return "unknown"           # 'unknown' is default host name
     except:
         pass
     return "unknown"           # 'unknown' is default host name
-    
+
 # ---
 
 def getAppName():
 # ---
 
 def getAppName():
@@ -194,8 +205,11 @@ def getPortNumber(use_default=True):
         return int( os.getenv( "NSPORT" ) )
     except:
         pass
         return int( os.getenv( "NSPORT" ) )
     except:
         pass
-    port = getPortFromORBcfg()
-    if port is not None: return port
+    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
 
     if use_default: return 2809 # '2809' is default port number
     return None
 
@@ -205,41 +219,27 @@ def getHomeDir():
     """
     Get home directory.
     """
     """
     Get home directory.
     """
-    import os, sys
-    if sys.platform == "win32":
-        # for Windows the home directory is detected in the following way:
-        # 1. try USERPROFILE env variable
-        # 2. try combination of HOMEDRIVE and HOMEPATH env variables
-        # 3. try HOME env variable
-        # TODO: on Windows, also GetUserProfileDirectoryW() system function might be used
-        dir = os.getenv("USERPROFILE")
-        if not dir and os.getenv("HOMEDRIVE") and os.getenv("HOMEPATH"):
-            dir = os.path.join(os.getenv("HOMEDRIVE"), os.getenv("HOMEPATH"))
-        if not dir:
-            dir = os.getenv("HOME")
-        pass
-    else:
-        # for Linux: use HOME variable
-        dir = os.getenv("HOME")
-        pass
-    return dir
+    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.
     """
 # ---
 
 def getTmpDir():
     """
     Get directory to be used for the temporary files.
     """
-    import os, sys
-    if sys.platform == "win32":
-        # for Windows: temporarily using home directory for tmp files;
-        # to be replaced with TEMP environment variable later...
-        dir = os.getenv("HOME")
-    else:
-        # for Linux: use /tmp/logs/{user} folder
-        dir = os.path.join( '/tmp', 'logs', getUserName() )
-        pass
-    return dir
-
+    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,
 # ---
 
 def generateFileName( dir, prefix = None, suffix = None, extension = None,
@@ -478,6 +478,7 @@ def verbose():
         pass
     #
     return _verbose
         pass
     #
     return _verbose
+# --
 
 def setVerbose(level):
     """
 
 def setVerbose(level):
     """
@@ -486,4 +487,107 @@ def setVerbose(level):
     global _verbose
     _verbose = level
     return
     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, 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=<caption0>
+        #   CommandLine=<commandline0>
+        #   ProcessId=<processid0>
+        #
+        #
+        #
+        #   Caption=<caption1>
+        #   CommandLine=<commandline1>
+        #   ProcessId=<processid1>
+        #   ...
+        cmd = 'WMIC PROCESS get Caption,Commandline,Processid /VALUE'
+        proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
+        # Get stdout
+        allProc = proc.communicate()[0]
+        # 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
+# --