-LRN: remove unused variables
[oweals/gnunet.git] / contrib / gnunet_janitor.py.in
1 #!@PYTHON@
2 #    This file is part of GNUnet.
3 #    (C) 2011 Christian Grothoff (and other contributing authors)
4 #
5 #    GNUnet is free software; you can redistribute it and/or modify
6 #    it under the terms of the GNU General Public License as published
7 #    by the Free Software Foundation; either version 2, or (at your
8 #    option) any later version.
9 #
10 #    GNUnet is distributed in the hope that it will be useful, but
11 #    WITHOUT ANY WARRANTY; without even the implied warranty of
12 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #    General Public License for more details.
14 #
15 #    You should have received a copy of the GNU General Public License
16 #    along with GNUnet; see the file COPYING.  If not, write to the
17 #    Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 #    Boston, MA 02111-1307, USA.
19 #
20 # Finds any gnunet processes still running in the system and kills them
21 #
22 # gnunet janitor can be used by invoking `make' like this:
23 # TESTS_ENVIRONMENT='${top_srcdir}/contrib/gnunet_janitor.py &&' make check
24
25 from __future__ import print_function
26 import os
27 import re
28 import subprocess
29 import sys
30 import shutil
31 import time
32 import signal
33
34 if os.name == 'nt':
35   from win32com.client import GetObject
36   WMI = GetObject('winmgmts:')
37   killsignal = signal.SIGTERM # any valid value will result in TerminateProcess()
38 else:
39   killsignal = signal.SIGKILL  
40
41 def get_process_list ():
42   result = []
43   if os.name == 'nt':
44     processes = WMI.InstancesOf('Win32_Process')
45     for p in processes:
46       result.append ((p.Properties_('ProcessId').Value, re.sub (r'(.+)\.exe', r'\1', p.Properties_('Name').Value)))
47   else:
48     pids = [pid for pid in os.listdir('/proc') if pid.isdigit ()]
49     for pid in pids:
50       with open (os.path.join ('/proc', pid, 'cmdline'), 'rb') as p:
51         cmdline = p.read ().split ('\x00')
52         if len (cmdline) > 0:
53           result.append ((pid, cmdline[0]))
54   return result
55
56 def main ():
57   procs = get_process_list ()
58   gnunet_procs = []
59   for p in procs:
60     if re.match (r'gnunet-.+', p[1]):
61       gnunet_procs.append (p)
62   for p in gnunet_procs:
63     if re.match (r'gnunet-service-arm', p[1]):
64       print ("killing arm process {0:5} {1}".format (p[0], p[1]))
65       try:
66         os.kill (int (p[0]), killsignal)
67       except OSError as e:
68         print ("failed: {0}".format (e))
69         pass
70   for p in gnunet_procs:
71     if not re.match (r'gnunet-service-arm', p[1]):
72       print ("killing non-arm process {0:5} {1}".format (p[0], p[1]))
73       try:
74         os.kill (int (p[0]), killsignal)
75       except OSError as e:
76         print ("failed: {0}".format (e))
77         pass
78
79 if __name__ == '__main__':
80   sys.exit (main ())