Salome HOME
0ffb397e3168e38b39cbba92c25ae2f1f04a274a
[modules/kernel.git] / bin / killSalomeWithPort.py
1 #! /usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2014  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, or (at your option) any later version.
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 import subprocess
36 import shlex
37 from salome_utils import verbose
38
39
40 def getPiDict(port,appname='salome',full=True,hidden=True,hostname=None):
41     """
42     Get file with list of SALOME processes.
43     This file is located in the user's home directory
44     and named .<user>_<host>_<port>_SALOME_pidict
45     where
46     <user> is user name
47     <host> is host name
48     <port> is port number
49
50     Parameters:
51     - port    : port number
52     - appname : application name (default is 'SALOME')
53     - full    : if True, full path to the file is returned, otherwise only file name is returned
54     - hidden  : if True, file name is prefixed with . (dot) symbol; this internal parameter is used
55     to support compatibility with older versions of SALOME
56     """
57     # bug fix: ensure port is an integer
58     # Note: this function is also called with port='#####' !!!
59     try:
60         port = int(port)
61     except:
62         pass
63
64     from salome_utils import generateFileName, getTmpDir
65     dir = ""
66     if not hostname:
67         hostname = os.getenv("NSHOST")
68         if hostname: hostname = hostname.split(".")[0]
69         pass
70     if full:
71         # full path to the pidict file is requested
72         if hidden:
73             # new-style dot-prefixed pidict files
74             # are in the system-dependant temporary diretory
75             dir = getTmpDir()
76         else:
77             # old-style non-dot-prefixed pidict files
78             # are in the user's home directory
79             dir = os.getenv("HOME")
80             pass
81         pass
82
83     return generateFileName(dir,
84                             suffix="pidict",
85                             hidden=hidden,
86                             with_username=True,
87                             with_hostname=hostname or True,
88                             with_port=port,
89                             with_app=appname.upper())
90
91 def appliCleanOmniOrbConfig(port):
92     """
93     Remove omniorb config files related to the port in SALOME application:
94     - ${OMNIORB_USER_PATH}/.omniORB_${USER}_${HOSTNAME}_${NSPORT}.cfg
95     - ${OMNIORB_USER_PATH}/.omniORB_${USER}_last.cfg
96     the last is removed only if the link points to the first file.
97     """
98     if verbose():
99         print "clean OmniOrb config for port %s"%port
100
101     from salome_utils import generateFileName, getUserName
102     omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
103     if omniorbUserPath is None:
104         #Run outside application context
105         pass
106     else:
107         omniorb_config      = generateFileName(omniorbUserPath, prefix="omniORB",
108                                                extension="cfg",
109                                                hidden=True,
110                                                with_username=True,
111                                                with_hostname=True,
112                                                with_port=port)
113         last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
114                                                with_username=True,
115                                                suffix="last",
116                                                extension="cfg",
117                                                hidden=True)
118         if os.access(last_running_config,os.F_OK):
119             if not sys.platform == 'win32':
120                 pointedPath = os.readlink(last_running_config)
121                 if pointedPath[0] != '/':
122                     pointedPath=os.path.join(os.path.dirname(last_running_config), pointedPath)
123                     pass
124                 if pointedPath == omniorb_config:
125                     os.unlink(last_running_config)
126                     pass
127                 pass
128             else:
129                 os.remove(last_running_config)
130                 pass
131             pass
132
133         if os.access(omniorb_config,os.F_OK):
134             os.remove(omniorb_config)
135             pass
136
137         if os.path.lexists(last_running_config):return
138
139         #try to relink last.cfg to an existing config file if any
140         files = glob.glob(os.path.join(omniorbUserPath,".omniORB_"+getUserName()+"_*.cfg"))
141         current_config=None
142         current=0
143         for f in files:
144           stat=os.stat(f)
145           if stat.st_atime > current:
146             current=stat.st_atime
147             current_config=f
148         if current_config:
149           if sys.platform == "win32":
150             import shutil
151             shutil.copyfile(os.path.normpath(current_config), last_running_config)
152             pass
153           else:
154             os.symlink(os.path.normpath(current_config), last_running_config)
155             pass
156           pass
157         pass
158     pass
159
160 ########## kills all salome processes with the given port ##########
161
162 def shutdownMyPort(port, cleanup=True):
163     """
164     Shutdown SALOME session running on the specified port.
165     Parameters:
166     - port - port number
167     """
168     if not port: return
169     # bug fix: ensure port is an integer
170     port = int(port)
171
172     try:
173         from PortManager import releasePort
174         releasePort(port)
175     except ImportError:
176         pass
177
178     from salome_utils import generateFileName
179
180     # set OMNIORB_CONFIG variable to the proper file
181     omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
182     kwargs = {}
183     if omniorbUserPath is not None:
184         kwargs["with_username"]=True
185     else:
186         omniorbUserPath = os.path.realpath(os.path.expanduser('~'))
187     omniorb_config = generateFileName(omniorbUserPath, prefix="omniORB",
188                                       extension="cfg",
189                                       hidden=True,
190                                       with_hostname=True,
191                                       with_port=port,
192                                       **kwargs)
193     os.environ['OMNIORB_CONFIG'] = omniorb_config
194     os.environ['NSPORT'] = str(port)
195
196     # give the chance to the servers to shutdown properly
197     try:
198         import time
199         from omniORB import CORBA
200         
201         from LifeCycleCORBA import LifeCycleCORBA
202         # shutdown all
203         orb = CORBA.ORB_init([''], CORBA.ORB_ID)
204         lcc = LifeCycleCORBA(orb)
205         lcc.shutdownServers()
206         # give some time to shutdown to complete
207         time.sleep(1)
208         # shutdown omniNames
209         if cleanup:
210             lcc.killOmniNames()
211             time.sleep(1)
212             pass
213         pass
214     except:
215         pass
216     pass
217
218 def __killMyPort(port, filedict):
219     # bug fix: ensure port is an integer
220     if port:
221         port = int(port)
222
223     try:
224         with open(filedict, 'r') as fpid:
225             #
226             from salome_utils import generateFileName
227             if sys.platform == "win32":
228                 username = os.getenv( "USERNAME" )
229                 tmpdir = 'c:\tmp'
230             else:
231                 username = os.getenv('USER')
232                 tmpdir = '/tmp'
233             path = os.path.join(tmpdir, 'logs', username)
234             fpidomniNames = generateFileName(path,
235                                              prefix="",
236                                              suffix="Pid_omniNames",
237                                              extension="log",
238                                              with_port=port)
239             if not sys.platform == 'win32':
240                 cmd = 'pid=$(ps -eo pid,command | egrep "[0-9] omniNames -start {0}") ; echo $pid > {1}'.format(port, fpidomniNames )
241                 subprocess.call(cmd, shell=True)
242                 pass
243             try:
244                 with open(fpidomniNames) as fpidomniNamesFile:
245                     lines = fpidomniNamesFile.readlines()
246
247                 os.remove(fpidomniNames)
248                 for l in lines:
249                     try:
250                         pidfield = l.split()[0] # pid should be at the first position
251                         if sys.platform == "win32":
252                             import win32pm #@UnresolvedImport
253                             if verbose(): print 'stop process '+pidfield+' : omniNames'
254                             win32pm.killpid(int(pidfield),0)
255                         else:
256                             if verbose(): print 'stop process '+pidfield+' : omniNames'
257                             os.kill(int(pidfield),signal.SIGKILL)
258                             pass
259                         pass
260                     except:
261                         pass
262                     pass
263                 pass
264             except:
265                 pass
266             #
267             try:
268                 process_ids=pickle.load(fpid)
269                 for process_id in process_ids:
270                     for pid, cmd in process_id.items():
271                         if verbose(): print "stop process %s : %s"% (pid, cmd[0])
272                         if cmd[0] == "omniNames":
273                             if not sys.platform == 'win32':
274                                 proc1 = subprocess.Popen(shlex.split('ps -eo pid,command'),stdout=subprocess.PIPE)
275                                 proc2 = subprocess.Popen(shlex.split('egrep "[0-9] omniNames -start"'),stdin=proc1.stdout, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
276                                 proc1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits.
277                                 out,_ = proc2.communicate()
278                                 # out looks like: PID omniNames -start PORT <other args>
279
280                                 # extract omninames pid and port number
281                                 try:
282                                     import re
283                                     omniNamesPid, omniNamesPort = re.search('(.+?) omniNames -start (.+?) ', out).group(1, 2)
284                                     if omniNamesPort == port:
285                                         if verbose():
286                                             print "stop omniNames [pid=%s] on port %s"%(omniNamesPid, omniNamesPort)
287                                         appliCleanOmniOrbConfig(omniNamesPort)
288                                         from PortManager import releasePort
289                                         releasePort(omniNamesPort)
290                                         os.kill(int(omniNamesPid),signal.SIGKILL)
291                                 except (ImportError, AttributeError, OSError):
292                                     pass
293                                 except:
294                                     import traceback
295                                     traceback.print_exc()
296
297                         try:
298                             if sys.platform == "win32":
299                                 import win32pm #@UnresolvedImport @Reimport
300                                 win32pm.killpid(int(pid),0)
301                             else:
302                                 os.kill(int(pid),signal.SIGKILL)
303                                 pass
304                             pass
305                         except:
306                             if verbose(): print "  ------------------ process %s : %s not found"% (pid, cmd[0])
307                             pass
308                         pass # for pid, cmd ...
309                     pass # for process_id ...
310                 pass # try...
311             except:
312                 pass
313         # end with
314         #
315         os.remove(filedict)
316         cmd='ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'" | sed -e "s%[^0-9]*\([0-9]*\) .*%\\1%g"'
317 #        pid = subprocess.check_output(shlex.split(cmd))
318         pid = commands.getoutput(cmd)
319         a = ""
320         while pid and len(a.split()) < 2:
321             a = commands.getoutput("kill -9 " + pid)
322             pid = commands.getoutput(cmd)
323             pass
324         pass
325     except:
326         print "Cannot find or open SALOME PIDs file for port", port
327         pass
328     #
329 #
330
331 def __guessPiDictFilename(port):
332     from salome_utils import getShortHostName, getHostName
333     filedicts = [
334         # new-style dot-prefixed pidict file
335         getPiDict(port, hidden=True),
336         # provide compatibility with old-style pidict file (not dot-prefixed)
337         getPiDict(port, hidden=False),
338         # provide compatibility with old-style pidict file (short hostname)
339         getPiDict(port, hidden=True, hostname=getShortHostName()),
340         # provide compatibility with old-style pidict file (not dot-prefixed, short hostname
341         getPiDict(port, hidden=False, hostname=getShortHostName()),
342         # provide compatibility with old-style pidict file (long hostname)
343         getPiDict(port, hidden=True, hostname=getHostName()),
344         # provide compatibility with old-style pidict file (not dot-prefixed, long hostname)
345         getPiDict(port, hidden=False, hostname=getHostName())
346         ]
347
348     log_msg = ""
349     for filedict in filedicts:
350         log_msg += "Trying %s..."%filedict
351         if os.path.exists(filedict):
352             log_msg += "   ... OK\n"
353             break
354         else:
355             log_msg += "   ... not found\n"
356
357     if verbose():
358         print log_msg
359
360     return filedict
361 #
362
363 def killMyPort(port):
364     """
365     Kill SALOME session running on the specified port.
366     Parameters:
367     - port - port number
368     """
369     print "Terminating SALOME on port %s..."%(port)
370
371     # bug fix: ensure port is an integer
372     if port:
373         port = int(port)
374
375     # try to shutdown session normally
376     import threading, time
377     threading.Thread(target=shutdownMyPort, args=(port,False)).start()
378     time.sleep(3) # wait a little, then kill processes (should be done if shutdown procedure hangs up)
379
380     try:
381         filedict = getPiDict(port)
382         #filedict = __guessPiDictFilename(port)
383         import glob
384         all_files = glob.glob("%s*"%filedict)
385         for f in all_files:
386             __killMyPort(port, f)
387     except ImportError:
388         filedict = __guessPiDictFilename(port)
389         __killMyPort(port, filedict)
390     #
391
392     appliCleanOmniOrbConfig(port)
393     pass
394
395 def cleanApplication(port):
396     """
397     Clean application running on the specified port.
398     Parameters:
399     - port - port number
400     """
401     # bug fix: ensure port is an integer
402     if port:
403         port = int(port)
404
405     try:
406         filedict=getPiDict(port)
407         os.remove(filedict)
408     except:
409       #import traceback
410       #traceback.print_exc()
411       pass
412
413     appliCleanOmniOrbConfig(port)
414
415 def killMyPortSpy(pid, port):
416     dt = 1.0
417     while 1:
418         if sys.platform == "win32":
419             from win32pm import killpid #@UnresolvedImport
420             if killpid(int(pid), 0) != 0:
421                 return
422         else:
423             from os import kill
424             try:
425                 kill(int(pid), 0)
426             except OSError, e:
427                 if e.errno != 3:
428                     return
429                 break
430             pass
431         from time import sleep
432         sleep(dt)
433         pass
434     filedict = getPiDict(port, hidden=True)
435     if not os.path.exists(filedict):
436         return
437     try:
438         import omniORB
439         orb = omniORB.CORBA.ORB_init(sys.argv, omniORB.CORBA.ORB_ID)
440         import SALOME_NamingServicePy
441         ns = SALOME_NamingServicePy.SALOME_NamingServicePy_i(orb)
442         import SALOME #@UnresolvedImport @UnusedImport
443         session = ns.Resolve("/Kernel/Session")
444         assert session
445     except:
446         return
447     try:
448         status = session.GetStatSession()
449     except:
450         # -- session is in naming service but has crash
451         status = None
452         pass
453     if status:
454         if not status.activeGUI:
455             return
456         pass
457     killMyPort(port)
458     return
459
460 if __name__ == "__main__":
461     if len(sys.argv) < 2:
462         print "Usage: "
463         print "  %s <port>" % os.path.basename(sys.argv[0])
464         print
465         print "Kills SALOME session running on specified <port>."
466         sys.exit(1)
467         pass
468     if sys.argv[1] == "--spy":
469         if len(sys.argv) > 3:
470             pid = sys.argv[2]
471             port = sys.argv[3]
472             killMyPortSpy(pid, port)
473             pass
474         sys.exit(0)
475         pass
476     try:
477         from salomeContextUtils import setOmniOrbUserPath #@UnresolvedImport
478         setOmniOrbUserPath()
479     except Exception, e:
480         print e
481         sys.exit(1)
482     for port in sys.argv[1:]:
483         killMyPort(port)
484         pass
485     pass