]> git.wh0rd.org - home.git/blob - .bin/gentoo-check-services
gentoo-check-services: add --dry-run and fix whitespace handling
[home.git] / .bin / gentoo-check-services
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 """Script for restarting services that refer to old/deleted libs."""
5
6 from __future__ import print_function
7
8 import argparse
9 import glob
10 import os
11 import signal
12 import sys
13 import time
14
15
16 # Set of paths that are "OK" and safe to ignore.
17 IGNORE_PATHS = set((
18 '/dev/zero',
19 '/etc/ld.so.cache',
20 ))
21
22
23 def find_svcs():
24 """Find all programs w/deleted paths."""
25 svcs = {}
26 for pid in os.listdir('/proc'):
27 try:
28 pid_nr = int(pid)
29 except ValueError:
30 continue
31
32 map = '/proc/%s/maps' % pid
33 if not os.path.exists(map):
34 print('skipping %s' % pid)
35 continue
36
37 old_paths = set()
38 for line in open(map):
39 if not line.endswith(' (deleted)\n'):
40 continue
41 # b71c7000-b7307000 rw-s 00000000 00:04 17024337 /dev/zero (deleted)
42 addr, perm, offset, dev, inode, path = line.split(' ', 5)
43 # Handle paths with spaces.
44 path = path.lstrip().rsplit(' ', 2)[0]
45 if (path == '/[aio]' or
46 path.startswith('/SYSV') or
47 path.startswith('/dev/shm/') or
48 path.startswith('/tmp/')):
49 continue
50 old_paths.add(path)
51
52 old_paths -= IGNORE_PATHS
53 if not old_paths:
54 continue
55
56 cmdline = open('/proc/%s/cmdline' % pid).read().split('\0')
57 try:
58 while True:
59 cmdline.remove('')
60 except ValueError:
61 pass
62 svcs[pid_nr] = {
63 'cmdline': cmdline,
64 'old_paths': old_paths,
65 }
66 return svcs
67
68
69 # Mapping of known programs to their init.d scripts.
70 SERVICES = {
71 '/usr/sbin/acpid': 'acpid',
72 '/usr/sbin/apache2': 'apache2',
73 '/usr/sbin/atd': 'atd',
74 '/usr/sbin/bacula-fd': 'bacula-fd',
75 '/usr/sbin/cron': 'vixie-cron',
76 '/usr/sbin/crond': 'dcron',
77 '/usr/sbin/snmpd': 'snmpd',
78 '/usr/sbin/sshd': 'sshd',
79 '/usr/sbin/syslog-ng': 'syslog-ng',
80 '/usr/sbin/xinetd': 'xinetd',
81 '/usr/bin/daisydog': 'daisydog',
82 '/usr/bin/distccd': 'distccd',
83 '/usr/bin/monit': 'monit',
84 '/usr/bin/stunnel': 'stunnel',
85 '/usr/bin/tor': 'tor',
86 '/usr/bin/transmission-daemon': 'transmission-daemon',
87 '/usr/bin/mediatomb': 'mediatomb',
88 '/lib/systemd/systemd-udevd': 'udev',
89 '/usr/libexec/nrpe': 'nrpe',
90 '/usr/libexec/postfix/master': 'postfix',
91 'denyhosts.py': 'denyhosts',
92 'dropbear': 'dropbear',
93 'galileo': 'galileo',
94 'tlsdated': 'tlsdated',
95 }
96 def auto_restart(opts, svcs):
97 kill = set()
98 restart = set()
99 for pid, svc in svcs.items():
100 if svc['cmdline'][0] == '/sbin/agetty':
101 kill.add(pid)
102 elif 'postgres:' in svc['cmdline'][0]:
103 p = os.path.basename(glob.glob('/etc/runlevels/default/postgresql-*')[0])
104 restart.add(p)
105 elif svc['cmdline'][0].startswith('metalog'):
106 restart.add('metalog')
107 else:
108 prog = svc['cmdline'][0]
109 if prog.startswith('/usr/bin/python'):
110 prog = os.path.basename(svc['cmdline'][1])
111
112 init = SERVICES.get(prog)
113 if init:
114 restart.add(init)
115
116 if kill or restart:
117 for pid in kill:
118 print('killing %s (%s)' % (pid, svcs[pid]['cmdline'][0]))
119 if not opts.dryrun:
120 os.kill(pid, signal.SIGTERM)
121 for init in restart:
122 print('restarting %s' % init)
123 if not opts.dryrun:
124 os.system('/etc/init.d/%s -q restart' % init)
125
126 if not opts.dryrun:
127 time.sleep(1)
128 svcs = find_svcs()
129
130 return svcs
131
132
133 def summarize(svcs):
134 print()
135 sslh = False
136 for pid in svcs.keys():
137 if svcs[pid]['cmdline'][0] == '/usr/sbin/sslh':
138 del svcs[pid]
139 sslh = True
140 if sslh:
141 print('sslh needs restart')
142
143 print()
144 for pid, svc in svcs.items():
145 print(pid, svc['cmdline'])
146 print('\t%s' % '\n\t'.join(svc['old_paths']))
147
148
149 def get_parser():
150 parser = argparse.ArgumentParser(description=__doc__)
151 parser.add_argument('-n', '--dry-run', dest='dryrun', action='store_true',
152 help='Show what would be restarted (and why)')
153 return parser
154
155
156 def main(argv):
157 parser = get_parser()
158 opts = parser.parse_args(argv)
159
160 svcs = find_svcs()
161 svcs = auto_restart(opts, svcs)
162 summarize(svcs)
163
164
165 if __name__ == '__main__':
166 exit(main(sys.argv[1:]))