Salome HOME
New CMake procedure.
[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 salome_utils import generateFileName
145
146     # set OMNIORB_CONFIG variable to the proper file
147     omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
148     kwargs = {}
149     if omniorbUserPath is not None:
150         kwargs["with_username"]=True
151     omniorb_config = generateFileName(omniorbUserPath, prefix="omniORB",
152                                       extension="cfg",
153                                       hidden=True,
154                                       with_hostname=True,
155                                       with_port=port,
156                                       **kwargs)
157     os.environ['OMNIORB_CONFIG'] = omniorb_config
158     os.environ['NSPORT'] = str(port)
159
160     # give the chance to the servers to shutdown properly
161     try:
162         import time
163         from omniORB import CORBA
164         from LifeCycleCORBA import LifeCycleCORBA
165         # shutdown all
166         orb = CORBA.ORB_init([''], CORBA.ORB_ID)
167         lcc = LifeCycleCORBA(orb)
168         lcc.shutdownServers()
169         # give some time to shutdown to complete
170         time.sleep(1)
171         # shutdown omniNames and notifd
172         if cleanup:
173             lcc.killOmniNames()
174             time.sleep(1)
175             pass
176         pass
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,False)).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 len(sys.argv) < 2:
359         print "Usage: "
360         print "  %s <port>" % os.path.basename(sys.argv[0])
361         print
362         print "Kills SALOME session running on specified <port>."
363         sys.exit(1)
364         pass
365     if sys.argv[1] == "--spy":
366         if len(sys.argv) > 3:
367             pid = sys.argv[2]
368             port = sys.argv[3]
369             killMyPortSpy(pid, port)
370             pass
371         sys.exit(0)
372         pass
373     for port in sys.argv[1:]:
374         killMyPort(port)
375         pass
376     pass