Salome HOME
Improve SALOME logger: customize log file name (add port, user and host ids) to avoid...
[modules/kernel.git] / bin / killSalomeWithPort.py
1 #!/usr/bin/env python
2
3 # Copyright (C) 2005  OPEN CASCADE, CEA, EDF R&D, LEG
4 #           PRINCIPIA R&D, EADS CCR, Lip6, BV, CEDRAT
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either 
8 # version 2.1 of the License.
9
10 # This library is distributed in the hope that it will be useful 
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of 
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
13 # Lesser General Public License for more details.
14
15 # You should have received a copy of the GNU Lesser General Public  
16 # License along with this library; if not, write to the Free Software 
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20
21
22 import os, sys, pickle, signal, commands
23 from launchConfigureParser import verbose
24
25 def getPiDict(port,appname='salome',full=True):
26     from Utils_Identity import getShortHostName
27
28     # get hostname by special function in all cases to
29     # have always same result in lower case at win32
30     host = getShortHostName()
31     if not host:
32         host = os.getenv("HOSTNAME")
33     if not host:
34         host = os.getenv("HOST")
35
36     filedict = []
37     filedict.append( os.getenv('USER') )          # user name
38     filedict.append( host )                       # host name
39     filedict.append( str(port) )                  # port number
40     filedict.append( appname.upper() )            # application name
41     filedict.append( 'pidict' )                   # constant part
42
43     filedict = '_'.join(filedict)
44     if full:
45         filedict = os.getenv("HOME") + '/' + filedict
46     return filedict
47
48 def appliCleanOmniOrbConfig(port):
49     """
50     remove omniorb config files related to the port in SALOME application:
51     - ${HOME}/${APPLI}/.omniORB_${HOSTNAME}_${NSPORT}.cfg
52     - ${HOME}/${APPLI}/.omniORB_last.cfg
53     the last is removed only if the link points to the first file.
54     """
55     from Utils_Identity import getShortHostName
56     appli=os.environ.get("APPLI")
57     if appli is None:
58         #Run outside application context
59         pass
60     else:
61         home = os.environ['HOME']
62         home='%s/%s'%(home,appli)
63         hostname=getShortHostName()
64         omniorb_config = '%s/.omniORB_%s_%s.cfg'%(home,hostname, str(port))
65         last_running_config = '%s/.omniORB_last.cfg'%(home)
66         if os.access(last_running_config,os.F_OK):
67             pointedPath = os.readlink(last_running_config)
68             if pointedPath[0] != '/':
69                 pointedPath=os.path.join(os.path.dirname(last_running_config), pointedPath)
70             if pointedPath == omniorb_config:
71                 os.unlink(last_running_config)
72                 pass
73             pass
74         if os.access(omniorb_config,os.F_OK):
75             os.remove(omniorb_config)
76             pass
77         pass
78
79 ########## kills all salome processes with the given port ##########
80
81 def killMyPort(port):
82     filedict=getPiDict(port)
83     found = 0
84     try:
85         fpid=open(filedict, 'r')
86         found = 1
87     except:
88         print "file %s giving SALOME process id is not readable"% filedict
89         pass
90         
91     if found:
92         if not sys.platform == 'win32':        
93             cmd = 'pid=`ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'"` ; echo $pid > /tmp/logs/'+os.getenv('USER')+"/_"+port+'_Pid_omniNames.log'
94             a = os.system(cmd)
95         try:
96             fpidomniNames=open('/tmp/logs/'+os.getenv('USER')+"/_"+port+'_Pid_omniNames.log')
97             prc = fpidomniNames.read()
98             fpidomniNames.close()
99             if prc != None :
100                 for field in prc.split(" ") :
101                     if field == "omniNames" :
102                         if pidfield != "egrep" :
103                             if sys.platform == "win32":
104                                 import win32pm
105                                 print 'stop process '+pidfield+' : omniNames'
106                                 win32pm.killpid(int(pidfield),0)
107                             else:
108                                 if verbose(): print 'stop process '+pidfield+' : omniNames'
109                                 os.system('kill -9 '+pidfield)
110                     pidfield = field
111         except:
112             pass
113         
114         try:
115             process_ids=pickle.load(fpid)
116             fpid.close()
117             for process_id in process_ids:
118
119                 for pid, cmd in process_id.items():
120                     if verbose(): print "stop process %s : %s"% (pid, cmd[0])
121                     try:
122                         if sys.platform == "win32":
123                           import win32pm
124                           win32pm.killpid(int(pid),0)
125                         else:
126                            os.kill(int(pid),signal.SIGKILL)
127                     except:
128                         if verbose(): print "  ------------------ process %s : %s not found"% (pid, cmd[0])
129                         pass
130                 pass
131         except:
132             pass
133         
134         os.remove(filedict)
135         cmd='ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'" | sed -e "s%[^0-9]*\([0-9]*\) .*%\\1%g"'
136         pid = commands.getoutput(cmd)
137         a = ""
138         while pid != "" and len(a.split(" ")) < 2:
139             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")
140             pid = commands.getoutput("ps -eo pid,command | egrep \"[0-9] omniNames -start "+str(port)+"\" | sed -e \"s%[^0-9]*\([0-9]*\) .*%\\1%g\"")
141             print pid
142             
143         pass
144
145     appliCleanOmniOrbConfig(port)
146     pass
147             
148
149 if __name__ == "__main__":
150     for port in sys.argv[1:]:
151         killMyPort(port)