Salome HOME
merge from branch BR_V5_DEV
[modules/yacs.git] / bin / killSalomeWithPort.py
1 #!/usr/bin/env python
2 #  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
3 #
4 #  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
5 #  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 #
7 #  This library is free software; you can redistribute it and/or
8 #  modify it under the terms of the GNU Lesser General Public
9 #  License as published by the Free Software Foundation; either
10 #  version 2.1 of the License.
11 #
12 #  This library is distributed in the hope that it will be useful,
13 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 #  Lesser General Public License for more details.
16 #
17 #  You should have received a copy of the GNU Lesser General Public
18 #  License along with this library; if not, write to the Free Software
19 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20 #
21 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 #
23 import os, sys, pickle, signal, commands,glob
24 from launchConfigureParser import verbose
25 import Utils_Identity
26 import salome_utils
27
28 def getPiDict(port,appname='salome',full=True,hidden=True):
29     """
30     Get file with list of SALOME processes.
31     This file is located in the user's home directory
32     and named .<user>_<host>_<port>_SALOME_pidict
33     where
34     <user> is user name
35     <host> is host name
36     <port> is port number
37
38     Parameters:
39     - port    : port number
40     - appname : application name (default is 'SALOME')
41     - full    : if True, full path to the file is returned, otherwise only file name is returned
42     - hidden  : if True, file name is prefixed with . (dot) symbol; this internal parameter is used
43     to support compatibility with older versions of SALOME
44     """
45     from salome_utils import generateFileName, getTmpDir
46     dir = ""
47     if full:
48         # full path to the pidict file is requested
49         if hidden:
50             # new-style dot-prefixed pidict files
51             # are in the system-dependant temporary diretory
52             dir = getTmpDir()
53         else:
54             # old-style non-dot-prefixed pidict files
55             # are in the user's home directory
56             dir = os.getenv("HOME")
57             pass
58         pass
59     return generateFileName(dir,
60                             suffix="pidict",
61                             hidden=hidden,
62                             with_username=True,
63                             with_hostname=True,
64                             with_port=port,
65                             with_app=appname.upper())
66
67 def appliCleanOmniOrbConfig(port):
68     """
69     Remove omniorb config files related to the port in SALOME application:
70     - ${HOME}/${APPLI}/USERS/.omniORB_${USER}_${HOSTNAME}_${NSPORT}.cfg
71     - ${HOME}/${APPLI}/USERS/.omniORB_${USER}_last.cfg
72     the last is removed only if the link points to the first file.
73     """
74     from salome_utils import generateFileName
75     home  = os.getenv("HOME")
76     appli = os.getenv("APPLI")
77     if appli is None:
78         #Run outside application context
79         pass
80     else:
81         dir = os.path.join(home, appli,"USERS")
82         omniorb_config      = generateFileName(dir, prefix="omniORB",
83                                                extension="cfg",
84                                                hidden=True,
85                                                with_username=True,
86                                                with_hostname=True,
87                                                with_port=port)
88         last_running_config = generateFileName(dir, prefix="omniORB",
89                                                with_username=True,
90                                                suffix="last",
91                                                extension="cfg",
92                                                hidden=True)
93         if os.access(last_running_config,os.F_OK):
94             pointedPath = os.readlink(last_running_config)
95             if pointedPath[0] != '/':
96                 pointedPath=os.path.join(os.path.dirname(last_running_config), pointedPath)
97             if pointedPath == omniorb_config:
98                 os.unlink(last_running_config)
99                 pass
100             pass
101         if os.access(omniorb_config,os.F_OK):
102             os.remove(omniorb_config)
103             pass
104
105         #try to relink last.cfg to an existing config file if any
106         files = glob.glob(os.path.join(os.environ["HOME"],Utils_Identity.getapplipath(),
107                                        "USERS",".omniORB_"+salome_utils.getUserName()+"_*.cfg"))
108         current_config=None
109         current=0
110         for f in files:
111           stat=os.stat(f)
112           if stat.st_atime > current:
113             current=stat.st_atime
114             current_config=f
115         if current_config:
116           os.symlink(os.path.normpath(current_config), last_running_config)
117
118         pass
119     pass
120
121 ########## kills all salome processes with the given port ##########
122
123 def killMyPort(port):
124     """
125     Kill SALOME session running on the specified port.
126     Parameters:
127     - port - port number
128     """
129     # new-style dot-prefixed pidict file
130     filedict = getPiDict(port, hidden=True)
131     # provide compatibility with old-style pidict file (not dot-prefixed)
132     if not os.path.exists(filedict): filedict = getPiDict(port, hidden=False)
133     #
134     try:
135         fpid = open(filedict, 'r')
136         #
137         from salome_utils import generateFileName
138         fpidomniNames = generateFileName(os.path.join('/tmp/logs', os.getenv('USER')),
139                                          prefix="",
140                                          suffix="Pid_omniNames",
141                                          extension="log",
142                                          with_port=port)
143         if not sys.platform == 'win32':        
144             cmd = 'pid=`ps -eo pid,command | egrep "[0-9] omniNames -start %s"` ; echo $pid > %s' % ( str(port), fpidomniNames )
145             a = os.system(cmd)
146             pass
147         try:
148             fpidomniNamesFile = open(fpidomniNames)
149             lines = fpidomniNamesFile.readlines()
150             fpidomniNamesFile.close()
151             os.remove(fpidomniNames)
152             for l in lines:
153                 try:
154                     pidfield = l.split()[0] # pid should be at the first position
155                     if sys.platform == "win32":
156                         import win32pm
157                         if verbose(): print 'stop process '+pidfield+' : omniNames'
158                         win32pm.killpid(int(pidfield),0)
159                     else:
160                         if verbose(): print 'stop process '+pidfield+' : omniNames'
161                         os.kill(int(pidfield),signal.SIGKILL)
162                         pass
163                     pass
164                 except:
165                     pass
166                 pass
167             pass
168         except:
169             pass
170         #
171         try:
172             process_ids=pickle.load(fpid)
173             fpid.close()
174             for process_id in process_ids:
175                 for pid, cmd in process_id.items():
176                     if verbose(): print "stop process %s : %s"% (pid, cmd[0])
177                     try:
178                         if sys.platform == "win32":
179                             import win32pm
180                             win32pm.killpid(int(pid),0)
181                         else:
182                             os.kill(int(pid),signal.SIGKILL)
183                             pass
184                         pass
185                     except:
186                         if verbose(): print "  ------------------ process %s : %s not found"% (pid, cmd[0])
187                         pass
188                     pass # for pid, cmd ...
189                 pass # for process_id ...
190             pass # try...
191         except:
192             pass
193         #
194         os.remove(filedict)
195         cmd='ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'" | sed -e "s%[^0-9]*\([0-9]*\) .*%\\1%g"'
196         pid = commands.getoutput(cmd)
197         a = ""
198         while pid and len(a.split()) < 2:
199             a = commands.getoutput("kill -9 " + pid)
200             pid = commands.getoutput(cmd)
201             #print pid
202             pass
203         pass
204     except:
205         print "Cannot find or open SALOME PIDs file for port", port
206         pass
207     #
208     appliCleanOmniOrbConfig(port)
209     pass
210             
211 def killNotifdAndClean(port):
212     """
213     Kill notifd daemon and clean application running on the specified port.
214     Parameters:
215     - port - port number
216     """
217     try:
218       filedict=getPiDict(port)
219       f=open(filedict, 'r')
220       pids=pickle.load(f)
221       for d in pids:
222         for pid,process in d.items():
223           if 'notifd' in process:
224             cmd='kill -9 %d'% pid
225             os.system(cmd)
226       os.remove(filedict)
227     except:
228       #import traceback
229       #traceback.print_exc()
230       pass
231
232     appliCleanOmniOrbConfig(port)
233     
234 if __name__ == "__main__":
235     for port in sys.argv[1:]:
236         killMyPort(port)
237         pass
238     pass