]> git.wh0rd.org Git - home.git/blob - .bin/gentoo-check-services
gentoo-check-services: tweak services
[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/ntpd': 'ntpd',
78         '/usr/sbin/snmpd': 'snmpd',
79         '/usr/sbin/sshd': 'sshd',
80         '/usr/sbin/syslog-ng': 'syslog-ng',
81         '/usr/sbin/xinetd': 'xinetd',
82         '/usr/bin/daisydog': 'daisydog',
83         '/usr/bin/distccd': 'distccd',
84         '/usr/bin/monit': 'monit',
85         '/usr/bin/stunnel': 'stunnel',
86         '/usr/bin/tor': 'tor',
87         '/usr/bin/transmission-daemon': 'transmission-daemon',
88         '/usr/bin/mediatomb': 'mediatomb',
89         '/lib/systemd/systemd-udevd': 'udev',
90         '/usr/libexec/nrpe': 'nrpe',
91         '//usr/libexec/postfix/master': 'postfix',
92         'denyhosts.py': 'denyhosts',
93         'dropbear': 'dropbear',
94         'galileo': 'galileo',
95         'tlsdated': 'tlsdated',
96 }
97 def auto_restart(opts, svcs):
98         kill = set()
99         restart = set()
100         for pid, svc in svcs.items():
101                 if svc['cmdline'][0] == '/sbin/agetty':
102                         kill.add(pid)
103                 elif 'postgres:' in svc['cmdline'][0]:
104                         p = os.path.basename(glob.glob('/etc/runlevels/default/postgresql-*')[0])
105                         restart.add(p)
106                 elif svc['cmdline'][0].startswith('metalog'):
107                         restart.add('metalog')
108                 else:
109                         prog = svc['cmdline'][0]
110                         if prog.startswith('/usr/bin/python'):
111                                 prog = os.path.basename(svc['cmdline'][1])
112
113                         init = SERVICES.get(prog)
114                         if init:
115                                 restart.add(init)
116
117         if kill or restart:
118                 for pid in kill:
119                         print('killing %s (%s)' % (pid, svcs[pid]['cmdline'][0]))
120                         if not opts.dryrun:
121                                 os.kill(pid, signal.SIGTERM)
122                 for init in restart:
123                         print('restarting %s' % init)
124                         if not opts.dryrun:
125                                 os.system('/etc/init.d/%s -q restart' % init)
126
127                 if not opts.dryrun:
128                         time.sleep(1)
129                         svcs = find_svcs()
130
131         return svcs
132
133
134 def summarize(svcs):
135         print()
136         sslh = False
137         for pid in svcs.keys():
138                 if svcs[pid]['cmdline'][0] == '/usr/sbin/sslh':
139                         del svcs[pid]
140                         sslh = True
141         if sslh:
142                 print('sslh needs restart')
143
144         print()
145         for pid, svc in svcs.items():
146                 print(pid, svc['cmdline'])
147                 print('\t%s' % '\n\t'.join(svc['old_paths']))
148
149
150 def get_parser():
151         parser = argparse.ArgumentParser(description=__doc__)
152         parser.add_argument('-n', '--dry-run', dest='dryrun', action='store_true',
153                             help='Show what would be restarted (and why)')
154         return parser
155
156
157 def main(argv):
158         parser = get_parser()
159         opts = parser.parse_args(argv)
160
161         svcs = find_svcs()
162         svcs = auto_restart(opts, svcs)
163         summarize(svcs)
164
165
166 if __name__ == '__main__':
167         exit(main(sys.argv[1:]))