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)
283 print "stop omniNames [pid=%s] on port %s"%(omniNamesPid, omniNamesPort)
284 appliCleanOmniOrbConfig(omniNamesPort)
285 from PortManager import releasePort
286 releasePort(omniNamesPort)
287 os.kill(int(omniNamesPid),signal.SIGKILL)
288 except (ImportError, AttributeError, OSError) as e:
292 traceback.print_exc()
295 if sys.platform == "win32":
297 win32pm.killpid(int(pid),0)
299 os.kill(int(pid),signal.SIGKILL)
303 if verbose(): print " ------------------ process %s : %s not found"% (pid, cmd[0])
305 pass # for pid, cmd ...
306 pass # for process_id ...
313 cmd='ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'" | sed -e "s%[^0-9]*\([0-9]*\) .*%\\1%g"'
314 pid = commands.getoutput(cmd)
316 while pid and len(a.split()) < 2:
317 a = commands.getoutput("kill -9 " + pid)
318 pid = commands.getoutput(cmd)
322 print "Cannot find or open SALOME PIDs file for port", port
327 def __guessPiDictFilename(port):
328 from salome_utils import getShortHostName, getHostName
330 # new-style dot-prefixed pidict file
331 getPiDict(port, hidden=True),
332 # provide compatibility with old-style pidict file (not dot-prefixed)
333 getPiDict(port, hidden=False),
334 # provide compatibility with old-style pidict file (short hostname)
335 getPiDict(port, hidden=True, hostname=getShortHostName()),
336 # provide compatibility with old-style pidict file (not dot-prefixed, short hostname
337 getPiDict(port, hidden=False, hostname=getShortHostName()),
338 # provide compatibility with old-style pidict file (long hostname)
339 getPiDict(port, hidden=True, hostname=getHostName()),
340 # provide compatibility with old-style pidict file (not dot-prefixed, long hostname)
341 getPiDict(port, hidden=False, hostname=getHostName())
345 for filedict in filedicts:
346 log_msg += "Trying %s..."%filedict
347 if os.path.exists(filedict):
348 log_msg += " ... OK\n"
351 log_msg += " ... not found\n"
359 def killMyPort(port):
361 Kill SALOME session running on the specified port.
365 print "Terminating SALOME on port %s..."%(port)
367 # bug fix: ensure port is an integer
371 # try to shutdown session normally
372 import threading, time
373 threading.Thread(target=shutdownMyPort, args=(port,False)).start()
374 time.sleep(3) # wait a little, then kill processes (should be done if shutdown procedure hangs up)
378 filedict = getPiDict(port)
379 #filedict = __guessPiDictFilename(port)
381 all_files = glob.glob("%s*"%filedict)
383 __killMyPort(port, f)
385 filedict = __guessPiDictFilename(port)
386 __killMyPort(port, filedict)
389 appliCleanOmniOrbConfig(port)
392 def cleanApplication(port):
394 Clean application running on the specified port.
398 # bug fix: ensure port is an integer
403 filedict=getPiDict(port)
407 #traceback.print_exc()
410 appliCleanOmniOrbConfig(port)
412 def killMyPortSpy(pid, port):
415 if sys.platform == "win32":
416 from win32pm import killpid
417 if killpid(int(pid), 0) != 0:
428 from time import sleep
431 filedict = getPiDict(port, hidden=True)
432 if not os.path.exists(filedict):
436 orb = omniORB.CORBA.ORB_init(sys.argv, omniORB.CORBA.ORB_ID)
437 import SALOME_NamingServicePy
438 ns = SALOME_NamingServicePy.SALOME_NamingServicePy_i(orb)
440 session = ns.Resolve("/Kernel/Session")
445 status = session.GetStatSession()
447 # -- session is in naming service but has crash
451 if not status.activeGUI:
457 if __name__ == "__main__":
458 if len(sys.argv) < 2:
460 print " %s <port>" % os.path.basename(sys.argv[0])
462 print "Kills SALOME session running on specified <port>."
465 if sys.argv[1] == "--spy":
466 if len(sys.argv) > 3:
469 killMyPortSpy(pid, port)
474 from salomeContextUtils import setOmniOrbUserPath
479 for port in sys.argv[1:]: