Salome HOME
Bug IPAL19893 4.x: debug information is in terminal.
[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,hidden=True):
26     """
27     Get file with list of SALOME processes.
28     This file is located in the user's home directory
29     and named .<user>_<host>_<port>_SALOME_pidict
30     where
31     <user> is user name
32     <host> is host name
33     <port> is port number
34
35     Parameters:
36     - port    : port number
37     - appname : application name (default is 'SALOME')
38     - full    : if True, full path to the file is returned, otherwise only file name is returned
39     - hidden  : if True, file name is prefixed with . (dot) symbol; this internal parameter is used
40     to support compatibility with older versions of SALOME
41     """
42     from salome_utilities import generateFileName, getTmpDir
43     dir = ""
44     if full:
45         # full path to the pidict file is requested
46         if hidden:
47             # new-style dot-prefixed pidict files
48             # are in the system-dependant temporary diretory
49             dir = getTmpDir()
50         else:
51             # old-style non-dot-prefixed pidict files
52             # are in the user's home directory
53             dir = os.getenv("HOME")
54             pass
55         pass
56     return generateFileName(dir,
57                             suffix="pidict",
58                             hidden=hidden,
59                             with_username=True,
60                             with_hostname=True,
61                             with_port=port,
62                             with_app=appname.upper())
63
64 def appliCleanOmniOrbConfig(port):
65     """
66     Remove omniorb config files related to the port in SALOME application:
67     - ${HOME}/${APPLI}/.omniORB_${HOSTNAME}_${NSPORT}.cfg
68     - ${HOME}/${APPLI}/.omniORB_last.cfg
69     the last is removed only if the link points to the first file.
70     """
71     from salome_utilities import generateFileName
72     home  = os.getenv("HOME")
73     appli = os.getenv("APPLI")
74     if appli is None:
75         #Run outside application context
76         pass
77     else:
78         dir = os.path.join(home, appli)
79         omniorb_config      = generateFileName(dir, prefix="omniORB",
80                                                extension="cfg",
81                                                hidden=True,
82                                                with_hostname=True,
83                                                with_port=port)
84         last_running_config = generateFileName(dir, prefix="omniORB",
85                                                suffix="last",
86                                                extension="cfg",
87                                                hidden=True)
88         if os.access(last_running_config,os.F_OK):
89             pointedPath = os.readlink(last_running_config)
90             if pointedPath[0] != '/':
91                 pointedPath=os.path.join(os.path.dirname(last_running_config), pointedPath)
92             if pointedPath == omniorb_config:
93                 os.unlink(last_running_config)
94                 pass
95             pass
96         if os.access(omniorb_config,os.F_OK):
97             os.remove(omniorb_config)
98             pass
99         pass
100     pass
101
102 ########## kills all salome processes with the given port ##########
103
104 def killMyPort(port):
105     """
106     Kill SALOME session running on the specified port.
107     Parameters:
108     - port - port number
109     """
110     # new-style dot-prefixed pidict file
111     filedict = getPiDict(port, hidden=True)
112     # provide compatibility with old-style pidict file (not dot-prefixed)
113     if not os.path.exists(filedict): filedict = getPiDict(port, hidden=False)
114     #
115     try:
116         fpid = open(filedict, 'r')
117         #
118         from salome_utilities import generateFileName
119         fpidomniNames = generateFileName(os.path.join('/tmp/logs', os.getenv('USER')),
120                                          prefix="",
121                                          suffix="Pid_omniNames",
122                                          extension="log",
123                                          with_port=port)
124         if not sys.platform == 'win32':        
125             cmd = 'pid=`ps -eo pid,command | egrep "[0-9] omniNames -start %s"` ; echo $pid > %s' % ( str(port), fpidomniNames )
126             a = os.system(cmd)
127             pass
128         try:
129             fpidomniNamesFile = open(fpidomniNames)
130             lines = fpidomniNamesFile.readlines()
131             fpidomniNamesFile.close()
132             os.remove(fpidomniNames)
133             for l in lines:
134                 try:
135                     pidfield = l.split()[0] # pid should be at the first position
136                     if sys.platform == "win32":
137                         import win32pm
138                         if verbose(): print 'stop process '+pidfield+' : omniNames'
139                         win32pm.killpid(int(pidfield),0)
140                     else:
141                         if verbose(): print 'stop process '+pidfield+' : omniNames'
142                         os.kill(int(pidfield),signal.SIGKILL)
143                         pass
144                     pass
145                 except:
146                     pass
147                 pass
148             pass
149         except:
150             pass
151         #
152         try:
153             process_ids=pickle.load(fpid)
154             fpid.close()
155             for process_id in process_ids:
156                 for pid, cmd in process_id.items():
157                     if verbose(): print "stop process %s : %s"% (pid, cmd[0])
158                     try:
159                         if sys.platform == "win32":
160                             import win32pm
161                             win32pm.killpid(int(pid),0)
162                         else:
163                             os.kill(int(pid),signal.SIGKILL)
164                             pass
165                         pass
166                     except:
167                         if verbose(): print "  ------------------ process %s : %s not found"% (pid, cmd[0])
168                         pass
169                     pass # for pid, cmd ...
170                 pass # for process_id ...
171             pass # try...
172         except:
173             pass
174         #
175         os.remove(filedict)
176         cmd='ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'" | sed -e "s%[^0-9]*\([0-9]*\) .*%\\1%g"'
177         pid = commands.getoutput(cmd)
178         a = ""
179         while pid and len(a.split()) < 2:
180             a = commands.getoutput("kill -9 " + pid)
181             pid = commands.getoutput(cmd)
182             #print pid
183             pass
184         pass
185     except:
186         print "Cannot find or open SALOME PIDs file for port", port
187         pass
188     #
189     appliCleanOmniOrbConfig(port)
190     pass
191             
192 if __name__ == "__main__":
193     for port in sys.argv[1:]:
194         killMyPort(port)
195         pass
196     pass