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