2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2014 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, or (at your option) any later version.
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 # bug fix: ensure port is an integer
56 # Note: this function is also called with port='#####' !!!
62 from salome_utils import generateFileName, getTmpDir
65 hostname = os.getenv("NSHOST")
66 if hostname: hostname = hostname.split(".")[0]
69 # full path to the pidict file is requested
71 # new-style dot-prefixed pidict files
72 # are in the system-dependant temporary diretory
75 # old-style non-dot-prefixed pidict files
76 # are in the user's home directory
77 dir = os.getenv("HOME")
81 return generateFileName(dir,
85 with_hostname=hostname or True,
87 with_app=appname.upper())
89 def appliCleanOmniOrbConfig(port):
91 Remove omniorb config files related to the port in SALOME application:
92 - ${OMNIORB_USER_PATH}/.omniORB_${USER}_${HOSTNAME}_${NSPORT}.cfg
93 - ${OMNIORB_USER_PATH}/.omniORB_${USER}_last.cfg
94 the last is removed only if the link points to the first file.
97 print "clean OmniOrb config for port %s"%port
99 from salome_utils import generateFileName, getUserName
100 omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
101 if omniorbUserPath is None:
102 #Run outside application context
105 omniorb_config = generateFileName(omniorbUserPath, prefix="omniORB",
111 last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
116 if os.access(last_running_config,os.F_OK):
117 if not sys.platform == 'win32':
118 pointedPath = os.readlink(last_running_config)
119 if pointedPath[0] != '/':
120 pointedPath=os.path.join(os.path.dirname(last_running_config), pointedPath)
122 if pointedPath == omniorb_config:
123 os.unlink(last_running_config)
127 os.remove(last_running_config)
131 if os.access(omniorb_config,os.F_OK):
132 os.remove(omniorb_config)
135 if os.path.lexists(last_running_config):return
137 #try to relink last.cfg to an existing config file if any
138 files = glob.glob(os.path.join(omniorbUserPath,".omniORB_"+getUserName()+"_*.cfg"))
143 if stat.st_atime > current:
144 current=stat.st_atime
147 if sys.platform == "win32":
149 shutil.copyfile(os.path.normpath(current_config), last_running_config)
152 os.symlink(os.path.normpath(current_config), last_running_config)
158 ########## kills all salome processes with the given port ##########
160 def shutdownMyPort(port, cleanup=True):
162 Shutdown SALOME session running on the specified port.
167 # bug fix: ensure port is an integer
171 from PortManager import releasePort
176 from salome_utils import generateFileName
178 # set OMNIORB_CONFIG variable to the proper file
179 omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
181 if omniorbUserPath is not None:
182 kwargs["with_username"]=True
184 omniorbUserPath = os.path.realpath(os.path.expanduser('~'))
185 omniorb_config = generateFileName(omniorbUserPath, prefix="omniORB",
191 os.environ['OMNIORB_CONFIG'] = omniorb_config
192 os.environ['NSPORT'] = str(port)
194 # give the chance to the servers to shutdown properly
197 from omniORB import CORBA
199 from LifeCycleCORBA import LifeCycleCORBA
201 orb = CORBA.ORB_init([''], CORBA.ORB_ID)
202 lcc = LifeCycleCORBA(orb)
203 lcc.shutdownServers()
204 # give some time to shutdown to complete
216 def __killMyPort(port, filedict):
217 # bug fix: ensure port is an integer
222 with open(filedict, 'r') as fpid:
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 with open(fpidomniNames) as fpidomniNamesFile:
241 lines = fpidomniNamesFile.readlines()
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)
265 for process_id in process_ids:
266 for pid, cmd in process_id.items():
267 if verbose(): print "stop process %s : %s"% (pid, cmd[0])
268 if cmd[0] == "omniNames":
269 if not sys.platform == 'win32':
272 proc1 = subprocess.Popen(shlex.split('ps -eo pid,command'),stdout=subprocess.PIPE)
273 proc2 = subprocess.Popen(shlex.split('egrep "[0-9] omniNames -start"'),stdin=proc1.stdout, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
274 proc1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits.
275 out,err=proc2.communicate()
276 # out looks like: PID omniNames -start PORT <other args>
278 # extract omninames pid and port number
281 omniNamesPid, omniNamesPort = re.search('(.+?) omniNames -start (.+?) ', out).group(1, 2)
282 if omniNamesPort == port:
284 print "stop omniNames [pid=%s] on port %s"%(omniNamesPid, omniNamesPort)
285 appliCleanOmniOrbConfig(omniNamesPort)
286 from PortManager import releasePort
287 releasePort(omniNamesPort)
288 os.kill(int(omniNamesPid),signal.SIGKILL)
289 except (ImportError, AttributeError, OSError) as e:
293 traceback.print_exc()
296 if sys.platform == "win32":
298 win32pm.killpid(int(pid),0)
300 os.kill(int(pid),signal.SIGKILL)
304 if verbose(): print " ------------------ process %s : %s not found"% (pid, cmd[0])
306 pass # for pid, cmd ...
307 pass # for process_id ...
314 cmd='ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'" | sed -e "s%[^0-9]*\([0-9]*\) .*%\\1%g"'
315 pid = commands.getoutput(cmd)
317 while pid and len(a.split()) < 2:
318 a = commands.getoutput("kill -9 " + pid)
319 pid = commands.getoutput(cmd)
323 print "Cannot find or open SALOME PIDs file for port", port
328 def __guessPiDictFilename(port):
329 from salome_utils import getShortHostName, getHostName
331 # new-style dot-prefixed pidict file
332 getPiDict(port, hidden=True),
333 # provide compatibility with old-style pidict file (not dot-prefixed)
334 getPiDict(port, hidden=False),
335 # provide compatibility with old-style pidict file (short hostname)
336 getPiDict(port, hidden=True, hostname=getShortHostName()),
337 # provide compatibility with old-style pidict file (not dot-prefixed, short hostname
338 getPiDict(port, hidden=False, hostname=getShortHostName()),
339 # provide compatibility with old-style pidict file (long hostname)
340 getPiDict(port, hidden=True, hostname=getHostName()),
341 # provide compatibility with old-style pidict file (not dot-prefixed, long hostname)
342 getPiDict(port, hidden=False, hostname=getHostName())
346 for filedict in filedicts:
347 log_msg += "Trying %s..."%filedict
348 if os.path.exists(filedict):
349 log_msg += " ... OK\n"
352 log_msg += " ... not found\n"
360 def killMyPort(port):
362 Kill SALOME session running on the specified port.
366 print "Terminating SALOME on port %s..."%(port)
368 # bug fix: ensure port is an integer
372 # try to shutdown session normally
373 import threading, time
374 threading.Thread(target=shutdownMyPort, args=(port,False)).start()
375 time.sleep(3) # wait a little, then kill processes (should be done if shutdown procedure hangs up)
379 filedict = getPiDict(port)
380 #filedict = __guessPiDictFilename(port)
382 all_files = glob.glob("%s*"%filedict)
384 __killMyPort(port, f)
386 filedict = __guessPiDictFilename(port)
387 __killMyPort(port, filedict)
390 appliCleanOmniOrbConfig(port)
393 def cleanApplication(port):
395 Clean application running on the specified port.
399 # bug fix: ensure port is an integer
404 filedict=getPiDict(port)
408 #traceback.print_exc()
411 appliCleanOmniOrbConfig(port)
413 def killMyPortSpy(pid, port):
416 if sys.platform == "win32":
417 from win32pm import killpid
418 if killpid(int(pid), 0) != 0:
429 from time import sleep
432 filedict = getPiDict(port, hidden=True)
433 if not os.path.exists(filedict):
437 orb = omniORB.CORBA.ORB_init(sys.argv, omniORB.CORBA.ORB_ID)
438 import SALOME_NamingServicePy
439 ns = SALOME_NamingServicePy.SALOME_NamingServicePy_i(orb)
441 session = ns.Resolve("/Kernel/Session")
446 status = session.GetStatSession()
448 # -- session is in naming service but has crash
452 if not status.activeGUI:
458 if __name__ == "__main__":
459 if len(sys.argv) < 2:
461 print " %s <port>" % os.path.basename(sys.argv[0])
463 print "Kills SALOME session running on specified <port>."
466 if sys.argv[1] == "--spy":
467 if len(sys.argv) > 3:
470 killMyPortSpy(pid, port)
475 from salomeContextUtils import setOmniOrbUserPath
480 for port in sys.argv[1:]: