Salome HOME
CCAR: change the hostname used for pidict file on remote machines (os.getenv["NSHOST...
[modules/kernel.git] / bin / killSalomeWithPort.py
1 #! /usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 #  Copyright (C) 2007-2010  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
25 ## \file killSalomeWithPort.py
26 #  Stop all %SALOME servers from given sessions by killing them
27 #
28 #  The sessions are indicated by their ports on the command line as in :
29 #  \code
30 #  killSalomeWithPort.py 2811 2815
31 #  \endcode
32 #
33
34 import os, sys, pickle, signal, commands,glob
35 from launchConfigureParser import verbose
36 import Utils_Identity
37 import salome_utils
38
39 def getPiDict(port,appname='salome',full=True,hidden=True):
40     """
41     Get file with list of SALOME processes.
42     This file is located in the user's home directory
43     and named .<user>_<host>_<port>_SALOME_pidict
44     where
45     <user> is user name
46     <host> is host name
47     <port> is port number
48
49     Parameters:
50     - port    : port number
51     - appname : application name (default is 'SALOME')
52     - full    : if True, full path to the file is returned, otherwise only file name is returned
53     - hidden  : if True, file name is prefixed with . (dot) symbol; this internal parameter is used
54     to support compatibility with older versions of SALOME
55     """
56     from salome_utils import generateFileName, getTmpDir
57     dir = ""
58     if full:
59         # full path to the pidict file is requested
60         if hidden:
61             # new-style dot-prefixed pidict files
62             # are in the system-dependant temporary diretory
63             dir = getTmpDir()
64         else:
65             # old-style non-dot-prefixed pidict files
66             # are in the user's home directory
67             dir = os.getenv("HOME")
68             pass
69         pass
70     return generateFileName(dir,
71                             suffix="pidict",
72                             hidden=hidden,
73                             with_username=True,
74                             with_hostname=os.getenv("NSHOST") or True,
75                             with_port=port,
76                             with_app=appname.upper())
77
78 def appliCleanOmniOrbConfig(port):
79     """
80     Remove omniorb config files related to the port in SALOME application:
81     - ${HOME}/${APPLI}/USERS/.omniORB_${USER}_${HOSTNAME}_${NSPORT}.cfg
82     - ${HOME}/${APPLI}/USERS/.omniORB_${USER}_last.cfg
83     the last is removed only if the link points to the first file.
84     """
85     from salome_utils import generateFileName
86     home  = os.getenv("HOME")
87     appli = os.getenv("APPLI")
88     if appli is None:
89         #Run outside application context
90         pass
91     else:
92         dir = os.path.join(home, appli,"USERS")
93         omniorb_config      = generateFileName(dir, prefix="omniORB",
94                                                extension="cfg",
95                                                hidden=True,
96                                                with_username=True,
97                                                with_hostname=True,
98                                                with_port=port)
99         last_running_config = generateFileName(dir, prefix="omniORB",
100                                                with_username=True,
101                                                suffix="last",
102                                                extension="cfg",
103                                                hidden=True)
104         if os.access(last_running_config,os.F_OK):
105             pointedPath = os.readlink(last_running_config)
106             if pointedPath[0] != '/':
107                 pointedPath=os.path.join(os.path.dirname(last_running_config), pointedPath)
108             if pointedPath == omniorb_config:
109                 os.unlink(last_running_config)
110                 pass
111             pass
112         if os.access(omniorb_config,os.F_OK):
113             os.remove(omniorb_config)
114             pass
115
116         if os.path.lexists(last_running_config):return 
117
118         #try to relink last.cfg to an existing config file if any
119         files = glob.glob(os.path.join(os.environ["HOME"],Utils_Identity.getapplipath(),
120                                        "USERS",".omniORB_"+salome_utils.getUserName()+"_*.cfg"))
121         current_config=None
122         current=0
123         for f in files:
124           stat=os.stat(f)
125           if stat.st_atime > current:
126             current=stat.st_atime
127             current_config=f
128         if current_config:
129           os.symlink(os.path.normpath(current_config), last_running_config)
130
131         pass
132     pass
133
134 ########## kills all salome processes with the given port ##########
135
136 def killMyPort(port):
137     """
138     Kill SALOME session running on the specified port.
139     Parameters:
140     - port - port number
141     """
142     # new-style dot-prefixed pidict file
143     filedict = getPiDict(port, hidden=True)
144     # provide compatibility with old-style pidict file (not dot-prefixed)
145     if not os.path.exists(filedict): filedict = getPiDict(port, hidden=False)
146     #
147     try:
148         fpid = open(filedict, 'r')
149         #
150         from salome_utils import generateFileName
151         if sys.platform == "win32":
152             username = os.getenv( "USERNAME" )
153         else:
154             username = os.getenv('USER')
155         path = os.path.join('/tmp/logs', username)
156         fpidomniNames = generateFileName(path,
157                                          prefix="",
158                                          suffix="Pid_omniNames",
159                                          extension="log",
160                                          with_port=port)
161         if not sys.platform == 'win32':        
162             cmd = 'pid=`ps -eo pid,command | egrep "[0-9] omniNames -start %s"` ; echo $pid > %s' % ( str(port), fpidomniNames )
163             a = os.system(cmd)
164             pass
165         try:
166             fpidomniNamesFile = open(fpidomniNames)
167             lines = fpidomniNamesFile.readlines()
168             fpidomniNamesFile.close()
169             os.remove(fpidomniNames)
170             for l in lines:
171                 try:
172                     pidfield = l.split()[0] # pid should be at the first position
173                     if sys.platform == "win32":
174                         import win32pm
175                         if verbose(): print 'stop process '+pidfield+' : omniNames'
176                         win32pm.killpid(int(pidfield),0)
177                     else:
178                         if verbose(): print 'stop process '+pidfield+' : omniNames'
179                         os.kill(int(pidfield),signal.SIGKILL)
180                         pass
181                     pass
182                 except:
183                     pass
184                 pass
185             pass
186         except:
187             pass
188         #
189         try:
190             process_ids=pickle.load(fpid)
191             fpid.close()
192             for process_id in process_ids:
193                 for pid, cmd in process_id.items():
194                     if verbose(): print "stop process %s : %s"% (pid, cmd[0])
195                     try:
196                         if sys.platform == "win32":
197                             import win32pm
198                             win32pm.killpid(int(pid),0)
199                         else:
200                             os.kill(int(pid),signal.SIGKILL)
201                             pass
202                         pass
203                     except:
204                         if verbose(): print "  ------------------ process %s : %s not found"% (pid, cmd[0])
205                         pass
206                     pass # for pid, cmd ...
207                 pass # for process_id ...
208             pass # try...
209         except:
210             pass
211         #
212         os.remove(filedict)
213         cmd='ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'" | sed -e "s%[^0-9]*\([0-9]*\) .*%\\1%g"'
214         pid = commands.getoutput(cmd)
215         a = ""
216         while pid and len(a.split()) < 2:
217             a = commands.getoutput("kill -9 " + pid)
218             pid = commands.getoutput(cmd)
219             #print pid
220             pass
221         pass
222     except:
223         print "Cannot find or open SALOME PIDs file for port", port
224         pass
225     #
226     appliCleanOmniOrbConfig(port)
227     pass
228             
229 def killNotifdAndClean(port):
230     """
231     Kill notifd daemon and clean application running on the specified port.
232     Parameters:
233     - port - port number
234     """
235     try:
236       filedict=getPiDict(port)
237       f=open(filedict, 'r')
238       pids=pickle.load(f)
239       for d in pids:
240         for pid,process in d.items():
241           if 'notifd' in process:
242             cmd='kill -9 %d'% pid
243             os.system(cmd)
244       os.remove(filedict)
245     except:
246       #import traceback
247       #traceback.print_exc()
248       pass
249
250     appliCleanOmniOrbConfig(port)
251     
252 if __name__ == "__main__":
253     for port in sys.argv[1:]:
254         killMyPort(port)
255         pass
256     pass