Salome HOME
add a runSalome.bat for windows
[modules/kernel.git] / bin / killSalomeWithPort.py
1 #!/usr/bin/env python
2 #  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
3 #
4 #  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
5 #  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 #
7 #  This library is free software; you can redistribute it and/or
8 #  modify it under the terms of the GNU Lesser General Public
9 #  License as published by the Free Software Foundation; either
10 #  version 2.1 of the License.
11 #
12 #  This library is distributed in the hope that it will be useful,
13 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 #  Lesser General Public License for more details.
16 #
17 #  You should have received a copy of the GNU Lesser General Public
18 #  License along with this library; if not, write to the Free Software
19 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20 #
21 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 #
23 ## \file killSalomeWithPort.py
24 #  Stop all %SALOME servers from given sessions by killing them
25 #
26 #   The sessions are indicated by their ports on the command line as in :
27 #
28 #    killSalomeWithPort.py 2811 2815
29 #
30
31 import os, sys, pickle, signal, commands,glob
32 from launchConfigureParser import verbose
33 import Utils_Identity
34 import salome_utils
35
36 def getPiDict(port,appname='salome',full=True,hidden=True):
37     """
38     Get file with list of SALOME processes.
39     This file is located in the user's home directory
40     and named .<user>_<host>_<port>_SALOME_pidict
41     where
42     <user> is user name
43     <host> is host name
44     <port> is port number
45
46     Parameters:
47     - port    : port number
48     - appname : application name (default is 'SALOME')
49     - full    : if True, full path to the file is returned, otherwise only file name is returned
50     - hidden  : if True, file name is prefixed with . (dot) symbol; this internal parameter is used
51     to support compatibility with older versions of SALOME
52     """
53     from salome_utils import generateFileName, getTmpDir
54     dir = ""
55     if full:
56         # full path to the pidict file is requested
57         if hidden:
58             # new-style dot-prefixed pidict files
59             # are in the system-dependant temporary diretory
60             dir = getTmpDir()
61         else:
62             # old-style non-dot-prefixed pidict files
63             # are in the user's home directory
64             dir = os.getenv("HOME")
65             pass
66         pass
67     return generateFileName(dir,
68                             suffix="pidict",
69                             hidden=hidden,
70                             with_username=True,
71                             with_hostname=True,
72                             with_port=port,
73                             with_app=appname.upper())
74
75 def appliCleanOmniOrbConfig(port):
76     """
77     Remove omniorb config files related to the port in SALOME application:
78     - ${HOME}/${APPLI}/USERS/.omniORB_${USER}_${HOSTNAME}_${NSPORT}.cfg
79     - ${HOME}/${APPLI}/USERS/.omniORB_${USER}_last.cfg
80     the last is removed only if the link points to the first file.
81     """
82     from salome_utils import generateFileName
83     home  = os.getenv("HOME")
84     appli = os.getenv("APPLI")
85     if appli is None:
86         #Run outside application context
87         pass
88     else:
89         dir = os.path.join(home, appli,"USERS")
90         omniorb_config      = generateFileName(dir, prefix="omniORB",
91                                                extension="cfg",
92                                                hidden=True,
93                                                with_username=True,
94                                                with_hostname=True,
95                                                with_port=port)
96         last_running_config = generateFileName(dir, prefix="omniORB",
97                                                with_username=True,
98                                                suffix="last",
99                                                extension="cfg",
100                                                hidden=True)
101         if os.access(last_running_config,os.F_OK):
102             pointedPath = os.readlink(last_running_config)
103             if pointedPath[0] != '/':
104                 pointedPath=os.path.join(os.path.dirname(last_running_config), pointedPath)
105             if pointedPath == omniorb_config:
106                 os.unlink(last_running_config)
107                 pass
108             pass
109         if os.access(omniorb_config,os.F_OK):
110             os.remove(omniorb_config)
111             pass
112
113         #try to relink last.cfg to an existing config file if any
114         files = glob.glob(os.path.join(os.environ["HOME"],Utils_Identity.getapplipath(),
115                                        "USERS",".omniORB_"+salome_utils.getUserName()+"_*.cfg"))
116         current_config=None
117         current=0
118         for f in files:
119           stat=os.stat(f)
120           if stat.st_atime > current:
121             current=stat.st_atime
122             current_config=f
123         if current_config:
124           os.symlink(os.path.normpath(current_config), last_running_config)
125
126         pass
127     pass
128
129 ########## kills all salome processes with the given port ##########
130
131 def killMyPort(port):
132     """
133     Kill SALOME session running on the specified port.
134     Parameters:
135     - port - port number
136     """
137     # new-style dot-prefixed pidict file
138     filedict = getPiDict(port, hidden=True)
139     # provide compatibility with old-style pidict file (not dot-prefixed)
140     if not os.path.exists(filedict): filedict = getPiDict(port, hidden=False)
141     #
142     try:
143         fpid = open(filedict, 'r')
144         #
145         from salome_utils import generateFileName
146         fpidomniNames = generateFileName(os.path.join('/tmp/logs', os.getenv('USER')),
147                                          prefix="",
148                                          suffix="Pid_omniNames",
149                                          extension="log",
150                                          with_port=port)
151         if not sys.platform == 'win32':        
152             cmd = 'pid=`ps -eo pid,command | egrep "[0-9] omniNames -start %s"` ; echo $pid > %s' % ( str(port), fpidomniNames )
153             a = os.system(cmd)
154             pass
155         try:
156             fpidomniNamesFile = open(fpidomniNames)
157             lines = fpidomniNamesFile.readlines()
158             fpidomniNamesFile.close()
159             os.remove(fpidomniNames)
160             for l in lines:
161                 try:
162                     pidfield = l.split()[0] # pid should be at the first position
163                     if sys.platform == "win32":
164                         import win32pm
165                         if verbose(): print 'stop process '+pidfield+' : omniNames'
166                         win32pm.killpid(int(pidfield),0)
167                     else:
168                         if verbose(): print 'stop process '+pidfield+' : omniNames'
169                         os.kill(int(pidfield),signal.SIGKILL)
170                         pass
171                     pass
172                 except:
173                     pass
174                 pass
175             pass
176         except:
177             pass
178         #
179         try:
180             process_ids=pickle.load(fpid)
181             fpid.close()
182             for process_id in process_ids:
183                 for pid, cmd in process_id.items():
184                     if verbose(): print "stop process %s : %s"% (pid, cmd[0])
185                     try:
186                         if sys.platform == "win32":
187                             import win32pm
188                             win32pm.killpid(int(pid),0)
189                         else:
190                             os.kill(int(pid),signal.SIGKILL)
191                             pass
192                         pass
193                     except:
194                         if verbose(): print "  ------------------ process %s : %s not found"% (pid, cmd[0])
195                         pass
196                     pass # for pid, cmd ...
197                 pass # for process_id ...
198             pass # try...
199         except:
200             pass
201         #
202         os.remove(filedict)
203         cmd='ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'" | sed -e "s%[^0-9]*\([0-9]*\) .*%\\1%g"'
204         pid = commands.getoutput(cmd)
205         a = ""
206         while pid and len(a.split()) < 2:
207             a = commands.getoutput("kill -9 " + pid)
208             pid = commands.getoutput(cmd)
209             #print pid
210             pass
211         pass
212     except:
213         print "Cannot find or open SALOME PIDs file for port", port
214         pass
215     #
216     appliCleanOmniOrbConfig(port)
217     pass
218             
219 def killNotifdAndClean(port):
220     """
221     Kill notifd daemon and clean application running on the specified port.
222     Parameters:
223     - port - port number
224     """
225     try:
226       filedict=getPiDict(port)
227       f=open(filedict, 'r')
228       pids=pickle.load(f)
229       for d in pids:
230         for pid,process in d.items():
231           if 'notifd' in process:
232             cmd='kill -9 %d'% pid
233             os.system(cmd)
234       os.remove(filedict)
235     except:
236       #import traceback
237       #traceback.print_exc()
238       pass
239
240     appliCleanOmniOrbConfig(port)
241     
242 if __name__ == "__main__":
243     for port in sys.argv[1:]:
244         killMyPort(port)
245         pass
246     pass