Salome HOME
57729aa88a3601a7e0a2ffd7647817b7acdfa1df
[modules/kernel.git] / bin / killSalomeWithPort.py
1 #! /usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2012  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 salome_utils import verbose
36 import Utils_Identity
37 import salome_utils
38
39 def getPiDict(port,appname='salome',full=True,hidden=True,hostname=None):
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 not hostname:
59         hostname = os.getenv("NSHOST")
60         if hostname: hostname = hostname.split(".")[0]
61         pass
62     if full:
63         # full path to the pidict file is requested
64         if hidden:
65             # new-style dot-prefixed pidict files
66             # are in the system-dependant temporary diretory
67             dir = getTmpDir()
68         else:
69             # old-style non-dot-prefixed pidict files
70             # are in the user's home directory
71             dir = os.getenv("HOME")
72             pass
73         pass
74     return generateFileName(dir,
75                             suffix="pidict",
76                             hidden=hidden,
77                             with_username=True,
78                             with_hostname=hostname or True,
79                             with_port=port,
80                             with_app=appname.upper())
81
82 def appliCleanOmniOrbConfig(port):
83     """
84     Remove omniorb config files related to the port in SALOME application:
85     - ${HOME}/${APPLI}/USERS/.omniORB_${USER}_${HOSTNAME}_${NSPORT}.cfg
86     - ${HOME}/${APPLI}/USERS/.omniORB_${USER}_last.cfg
87     the last is removed only if the link points to the first file.
88     """
89     from salome_utils import generateFileName, getUserName
90     home  = os.getenv("HOME")
91     appli = os.getenv("APPLI")
92     if appli is None:
93         #Run outside application context
94         pass
95     else:
96         dir = os.path.join(os.path.realpath(home), appli,"USERS")
97         omniorb_config      = generateFileName(dir, prefix="omniORB",
98                                                extension="cfg",
99                                                hidden=True,
100                                                with_username=True,
101                                                with_hostname=True,
102                                                with_port=port)
103         last_running_config = generateFileName(dir, prefix="omniORB",
104                                                with_username=True,
105                                                suffix="last",
106                                                extension="cfg",
107                                                hidden=True)
108         if os.access(last_running_config,os.F_OK):
109             pointedPath = os.readlink(last_running_config)
110             if pointedPath[0] != '/':
111                 pointedPath=os.path.join(os.path.dirname(last_running_config), pointedPath)
112             if pointedPath == omniorb_config:
113                 os.unlink(last_running_config)
114                 pass
115             pass
116         if os.access(omniorb_config,os.F_OK):
117             os.remove(omniorb_config)
118             pass
119
120         if os.path.lexists(last_running_config):return 
121
122         #try to relink last.cfg to an existing config file if any
123         files = glob.glob(os.path.join(os.environ["HOME"],Utils_Identity.getapplipath(),
124                                        "USERS",".omniORB_"+getUserName()+"_*.cfg"))
125         current_config=None
126         current=0
127         for f in files:
128           stat=os.stat(f)
129           if stat.st_atime > current:
130             current=stat.st_atime
131             current_config=f
132         if current_config:
133           os.symlink(os.path.normpath(current_config), last_running_config)
134
135         pass
136     pass
137
138 ########## kills all salome processes with the given port ##########
139
140 def shutdownMyPort(port):
141     """
142     Shutdown SALOME session running on the specified port.
143     Parameters:
144     - port - port number
145     """
146     if not port: return
147     
148     from salome_utils import generateFileName
149
150     # set OMNIORB_CONFIG variable to the proper file
151     home  = os.getenv("HOME")
152     appli = os.getenv("APPLI")
153     kwargs = {}
154     if appli is not None: 
155         home = os.path.join(os.path.realpath(home), appli,"USERS")
156         kwargs["with_username"]=True
157         pass
158     omniorb_config = generateFileName(home, prefix="omniORB",
159                                       extension="cfg",
160                                       hidden=True,
161                                       with_hostname=True,
162                                       with_port=port,
163                                       **kwargs)
164     os.environ['OMNIORB_CONFIG'] = omniorb_config
165
166     # give the chance to the servers to shutdown properly
167     try:
168         import time
169         import salome_kernel
170         orb, lcc, naming_service, cm = salome_kernel.salome_kernel_init()
171         # shutdown all
172         lcc.shutdownServers()
173         # give some time to shutdown to complete
174         time.sleep(1)
175         # shutdown omniNames and notifd
176         salome_kernel.LifeCycleCORBA.killOmniNames()
177     except:
178         pass
179     pass
180     
181 def killMyPort(port):
182     """
183     Kill SALOME session running on the specified port.
184     Parameters:
185     - port - port number
186     """
187     from salome_utils import getShortHostName, getHostName
188     
189     # try to shutdown session nomally
190     import threading, time
191     threading.Thread(target=shutdownMyPort, args=(port,)).start()
192     time.sleep(3) # wait a little, then kill processes (should be done if shutdown procedure hangs up)
193     
194     # new-style dot-prefixed pidict file
195     filedict = getPiDict(port, hidden=True)
196     # provide compatibility with old-style pidict file (not dot-prefixed)
197     if not os.path.exists(filedict): filedict = getPiDict(port, hidden=False)
198     # provide compatibility with old-style pidict file (short hostname)
199     if not os.path.exists(filedict): filedict = getPiDict(port, hidden=True,  hostname=getShortHostName())
200     # provide compatibility with old-style pidict file (not dot-prefixed, short hostname)
201     if not os.path.exists(filedict): filedict = getPiDict(port, hidden=False, hostname=getShortHostName())
202     # provide compatibility with old-style pidict file (long hostname)
203     if not os.path.exists(filedict): filedict = getPiDict(port, hidden=True,  hostname=getHostName())
204     # provide compatibility with old-style pidict file (not dot-prefixed, long hostname)
205     if not os.path.exists(filedict): filedict = getPiDict(port, hidden=False, hostname=getHostName())
206     #
207     try:
208         fpid = open(filedict, 'r')
209         #
210         from salome_utils import generateFileName
211         if sys.platform == "win32":
212             username = os.getenv( "USERNAME" )
213         else:
214             username = os.getenv('USER')
215         path = os.path.join('/tmp/logs', username)
216         fpidomniNames = generateFileName(path,
217                                          prefix="",
218                                          suffix="Pid_omniNames",
219                                          extension="log",
220                                          with_port=port)
221         if not sys.platform == 'win32':        
222             cmd = 'pid=`ps -eo pid,command | egrep "[0-9] omniNames -start %s"` ; echo $pid > %s' % ( str(port), fpidomniNames )
223             a = os.system(cmd)
224             pass
225         try:
226             fpidomniNamesFile = open(fpidomniNames)
227             lines = fpidomniNamesFile.readlines()
228             fpidomniNamesFile.close()
229             os.remove(fpidomniNames)
230             for l in lines:
231                 try:
232                     pidfield = l.split()[0] # pid should be at the first position
233                     if sys.platform == "win32":
234                         import win32pm
235                         if verbose(): print 'stop process '+pidfield+' : omniNames'
236                         win32pm.killpid(int(pidfield),0)
237                     else:
238                         if verbose(): print 'stop process '+pidfield+' : omniNames'
239                         os.kill(int(pidfield),signal.SIGKILL)
240                         pass
241                     pass
242                 except:
243                     pass
244                 pass
245             pass
246         except:
247             pass
248         #
249         try:
250             process_ids=pickle.load(fpid)
251             fpid.close()
252             for process_id in process_ids:
253                 for pid, cmd in process_id.items():
254                     if verbose(): print "stop process %s : %s"% (pid, cmd[0])
255                     try:
256                         if sys.platform == "win32":
257                             import win32pm
258                             win32pm.killpid(int(pid),0)                            
259                         else:
260                             os.kill(int(pid),signal.SIGKILL)
261                             pass
262                         pass
263                     except:
264                         if verbose(): print "  ------------------ process %s : %s not found"% (pid, cmd[0])
265                         pass
266                     pass # for pid, cmd ...
267                 pass # for process_id ...
268             pass # try...
269         except:
270             pass
271         #
272         os.remove(filedict)
273         cmd='ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'" | sed -e "s%[^0-9]*\([0-9]*\) .*%\\1%g"'
274         pid = commands.getoutput(cmd)
275         a = ""
276         while pid and len(a.split()) < 2:
277             a = commands.getoutput("kill -9 " + pid)
278             pid = commands.getoutput(cmd)
279             #print pid
280             pass
281         pass
282     except:
283         print "Cannot find or open SALOME PIDs file for port", port
284         pass
285     #
286     appliCleanOmniOrbConfig(port)
287     pass
288             
289 def killNotifdAndClean(port):
290     """
291     Kill notifd daemon and clean application running on the specified port.
292     Parameters:
293     - port - port number
294     """
295     try:
296       filedict=getPiDict(port)
297       f=open(filedict, 'r')
298       pids=pickle.load(f)
299       for d in pids:
300         for pid,process in d.items():
301           if 'notifd' in process:
302             cmd='kill -9 %d'% pid
303             os.system(cmd)
304       os.remove(filedict)
305     except:
306       #import traceback
307       #traceback.print_exc()
308       pass
309
310     appliCleanOmniOrbConfig(port)
311
312 def killMyPortSpy(pid, port):
313     dt = 1.0
314     while 1:
315         if sys.platform == "win32":
316             from win32pm import killpid
317             if killpid(int(pid), 0) != 0:
318                 return
319         else:
320             from os import kill
321             try:
322                 kill(int(pid), 0)
323             except OSError, e:
324                 if e.errno != 3:
325                     return
326                 break
327             pass
328         from time import sleep
329         sleep(dt)
330         pass
331     filedict = getPiDict(port, hidden=True)
332     if not os.path.exists(filedict):
333         return
334     try:
335         import omniORB
336         orb = omniORB.CORBA.ORB_init(sys.argv, omniORB.CORBA.ORB_ID)
337         import SALOME_NamingServicePy
338         ns = SALOME_NamingServicePy.SALOME_NamingServicePy_i(orb)
339         import SALOME
340         session = ns.Resolve("/Kernel/Session")
341         assert session
342     except:
343         return
344     try:
345         status = session.GetStatSession()
346     except:
347         # -- session is in naming service but has crash
348         status = None
349         pass
350     if status:
351         if not status.activeGUI:
352             return
353         pass
354     killMyPort(port)
355     return
356
357 if __name__ == "__main__":
358     if sys.argv[1] == "--spy":
359         pid = sys.argv[2]
360         port = sys.argv[3]
361         killMyPortSpy(pid, port)
362         sys.exit(0)
363         pass
364     for port in sys.argv[1:]:
365         killMyPort(port)
366         pass
367     pass