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