2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE
5 # Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
22 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
25 ## \file killSalomeWithPort.py
26 # Stop all %SALOME servers from given sessions by killing them
28 # The sessions are indicated by their ports on the command line as in :
30 # killSalomeWithPort.py 2811 2815
34 import os, sys, pickle, signal, commands,glob
35 from salome_utils import verbose
38 def getPiDict(port,appname='salome',full=True,hidden=True,hostname=None):
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
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
55 from salome_utils import generateFileName, getTmpDir
58 hostname = os.getenv("NSHOST")
59 if hostname: hostname = hostname.split(".")[0]
62 # full path to the pidict file is requested
64 # new-style dot-prefixed pidict files
65 # are in the system-dependant temporary diretory
68 # old-style non-dot-prefixed pidict files
69 # are in the user's home directory
70 dir = os.getenv("HOME")
73 return generateFileName(dir,
77 with_hostname=hostname or True,
79 with_app=appname.upper())
81 def appliCleanOmniOrbConfig(port):
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.
88 from salome_utils import generateFileName, getUserName
89 omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
90 if omniorbUserPath is None:
91 #Run outside application context
94 omniorb_config = generateFileName(omniorbUserPath, prefix="omniORB",
100 last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
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)
113 if os.access(omniorb_config,os.F_OK):
114 os.remove(omniorb_config)
117 if os.path.lexists(last_running_config):return
119 #try to relink last.cfg to an existing config file if any
120 files = glob.glob(os.path.join(omniorbUserPath,".omniORB_"+getUserName()+"_*.cfg"))
125 if stat.st_atime > current:
126 current=stat.st_atime
129 os.symlink(os.path.normpath(current_config), last_running_config)
134 ########## kills all salome processes with the given port ##########
136 def shutdownMyPort(port, cleanup=True):
138 Shutdown SALOME session running on the specified port.
145 from PortManager import releasePort
150 from salome_utils import generateFileName
152 # set OMNIORB_CONFIG variable to the proper file
153 omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
155 if omniorbUserPath is not None:
156 kwargs["with_username"]=True
158 omniorbUserPath = os.path.realpath(os.path.expanduser('~'))
159 omniorb_config = generateFileName(omniorbUserPath, prefix="omniORB",
165 os.environ['OMNIORB_CONFIG'] = omniorb_config
166 os.environ['NSPORT'] = str(port)
168 # give the chance to the servers to shutdown properly
171 from omniORB import CORBA
172 from LifeCycleCORBA import LifeCycleCORBA
174 orb = CORBA.ORB_init([''], CORBA.ORB_ID)
175 lcc = LifeCycleCORBA(orb)
176 lcc.shutdownServers()
177 # give some time to shutdown to complete
179 # shutdown omniNames and notifd
189 def killMyPort(port):
191 Kill SALOME session running on the specified port.
197 PortManager.releasePort(port)
201 from salome_utils import getShortHostName, getHostName
203 # try to shutdown session nomally
204 import threading, time
205 threading.Thread(target=shutdownMyPort, args=(port,False)).start()
206 time.sleep(3) # wait a little, then kill processes (should be done if shutdown procedure hangs up)
208 # new-style dot-prefixed pidict file
209 filedict = getPiDict(port, hidden=True)
210 # provide compatibility with old-style pidict file (not dot-prefixed)
211 if not os.path.exists(filedict): filedict = getPiDict(port, hidden=False)
212 # provide compatibility with old-style pidict file (short hostname)
213 if not os.path.exists(filedict): filedict = getPiDict(port, hidden=True, hostname=getShortHostName())
214 # provide compatibility with old-style pidict file (not dot-prefixed, short hostname)
215 if not os.path.exists(filedict): filedict = getPiDict(port, hidden=False, hostname=getShortHostName())
216 # provide compatibility with old-style pidict file (long hostname)
217 if not os.path.exists(filedict): filedict = getPiDict(port, hidden=True, hostname=getHostName())
218 # provide compatibility with old-style pidict file (not dot-prefixed, long hostname)
219 if not os.path.exists(filedict): filedict = getPiDict(port, hidden=False, hostname=getHostName())
222 fpid = open(filedict, 'r')
224 from salome_utils import generateFileName
225 if sys.platform == "win32":
226 username = os.getenv( "USERNAME" )
228 username = os.getenv('USER')
229 path = os.path.join('/tmp/logs', username)
230 fpidomniNames = generateFileName(path,
232 suffix="Pid_omniNames",
235 if not sys.platform == 'win32':
236 cmd = 'pid=`ps -eo pid,command | egrep "[0-9] omniNames -start %s"` ; echo $pid > %s' % ( str(port), fpidomniNames )
240 fpidomniNamesFile = open(fpidomniNames)
241 lines = fpidomniNamesFile.readlines()
242 fpidomniNamesFile.close()
243 os.remove(fpidomniNames)
246 pidfield = l.split()[0] # pid should be at the first position
247 if sys.platform == "win32":
249 if verbose(): print 'stop process '+pidfield+' : omniNames'
250 win32pm.killpid(int(pidfield),0)
252 if verbose(): print 'stop process '+pidfield+' : omniNames'
253 os.kill(int(pidfield),signal.SIGKILL)
264 process_ids=pickle.load(fpid)
266 for process_id in process_ids:
267 for pid, cmd in process_id.items():
268 if verbose(): print "stop process %s : %s"% (pid, cmd[0])
270 if sys.platform == "win32":
272 win32pm.killpid(int(pid),0)
274 os.kill(int(pid),signal.SIGKILL)
278 if verbose(): print " ------------------ process %s : %s not found"% (pid, cmd[0])
280 pass # for pid, cmd ...
281 pass # for process_id ...
287 cmd='ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'" | sed -e "s%[^0-9]*\([0-9]*\) .*%\\1%g"'
288 pid = commands.getoutput(cmd)
290 while pid and len(a.split()) < 2:
291 a = commands.getoutput("kill -9 " + pid)
292 pid = commands.getoutput(cmd)
297 print "Cannot find or open SALOME PIDs file for port", port
300 appliCleanOmniOrbConfig(port)
303 def killNotifdAndClean(port):
305 Kill notifd daemon and clean application running on the specified port.
310 filedict=getPiDict(port)
311 f=open(filedict, 'r')
314 for pid,process in d.items():
315 if 'notifd' in process:
316 cmd='kill -9 %d'% pid
321 #traceback.print_exc()
324 appliCleanOmniOrbConfig(port)
326 def killMyPortSpy(pid, port):
329 if sys.platform == "win32":
330 from win32pm import killpid
331 if killpid(int(pid), 0) != 0:
342 from time import sleep
345 filedict = getPiDict(port, hidden=True)
346 if not os.path.exists(filedict):
350 orb = omniORB.CORBA.ORB_init(sys.argv, omniORB.CORBA.ORB_ID)
351 import SALOME_NamingServicePy
352 ns = SALOME_NamingServicePy.SALOME_NamingServicePy_i(orb)
354 session = ns.Resolve("/Kernel/Session")
359 status = session.GetStatSession()
361 # -- session is in naming service but has crash
365 if not status.activeGUI:
371 if __name__ == "__main__":
372 if len(sys.argv) < 2:
374 print " %s <port>" % os.path.basename(sys.argv[0])
376 print "Kills SALOME session running on specified <port>."
379 if sys.argv[1] == "--spy":
380 if len(sys.argv) > 3:
383 killMyPortSpy(pid, port)
387 for port in sys.argv[1:]: