summaryrefslogtreecommitdiff
path: root/whatmaps
blob: 7a90303180d1a3546bb23407b701cadf41c20f91 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
#!/usr/bin/python -u
# vim: set fileencoding=utf-8 :
#
# (C) 2010 Guido Guenther <agx@sigxcpu.org>
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import glob
import os
import logging
import re
import subprocess
import sys
from optparse import OptionParser


class PkgError(Exception):
    pass


class Process(object):
    """A process, needs /proc mounted"""
    deleted_re = re.compile(r"(?P<exe>.*) \(deleted\)$")

    def __init__(self, pid):
        self.pid = pid
        self.mapped = []
        try:
            # Linux only so far
            self.exe = os.readlink('/proc/%d/exe' % self.pid)
            if not os.path.exists(self.exe):
                    m = self.deleted_re.match(self.exe)
                    if m:
                        self.exe = m.group('exe')
                        logging.debug("Using deleted exe %s", self.exe)
                    else:
                        logging.debug("%s doesn't exist", self.exe)
            self.cmdline = open('/proc/%d/cmdline' % self.pid).read()
        except OSError:
            self.exe = None
            self.cmdline = None

    def _read_maps(self):
        for line in file('/proc/%d/maps' % self.pid):
            try:
                so = line.split()[5].strip()
                self.mapped.append(so)
            except IndexError:
                pass

    def maps(self, path):
        """check if process maps the object at path"""
        if not self.mapped:
            self._read_maps()

        if path in self.mapped:
            return True
        else:
            return False

    def __repr__(self):
        return "<Process object pid:%d>" % self.pid


class Distro(object):
    @classmethod
    def pkg(klass, path):
        raise NotImplementedError

    @classmethod
    def pkg_by_file(klass, path):
        raise NotImplementedError

    @classmethod
    def pkg_services(klass, pkg):
        try:
            return klass._pkg_services[pkg.name]
        except KeyError, AttributeError:
            return []


class Pkg(object):
    services = None
    shared_objects = None
    _so_regex = re.compile(r'(?P<so>/.*\.so(\.[^/])*$)')

    def __init__(self, name):
        self.name = name
        self._services = None
        self._shared_objects = None
        self._contents = None

    def __repr__(self):
        return "<%s Pkg object name:'%s'>" % (self.type, self.name)

    def _get_contents(self):
        if self._contents:
            return self._contents
        else:
            list_contents = subprocess.Popen([self._list_contents % self.name],
                                             stdout=subprocess.PIPE, shell=True)
        output = list_contents.communicate()[0]
        if list_contents.returncode:
            raise PkgError
        self.contents = output.split('\n')
        return self.contents


class DebianDistro(Distro):
    "Debian (dpkg) based distribution"""
    id = 'Debian'

    _pkg_services = { 'apache2-mpm-worker':  [ 'apache2' ],
                      'apache2-mpm-prefork': [ 'apache2' ],
                      'dovecot-imapd':       [ 'dovecot' ],
                      'dovecot-pop3d':       [ 'dovecot' ],
                    }

    @classmethod
    def pkg(klass, name):
        return DebianPkg(name)

    @classmethod
    def pkg_by_file(klass, path):
        find_file = subprocess.Popen(["dpkg-query -S %s 2>/dev/null" % path],
                                      stdout=subprocess.PIPE, shell=True)
        output = find_file.communicate()[0]
        if find_file.returncode:
            return None
        pkg = output.split(':')[0]
        return DebianPkg(pkg)

    @classmethod
    def restart_service(klass, name):
        subprocess.call('invoke-rc.d %s restart' % name, shell = True)


class DebianPkg(Pkg):
    type = 'Debian'
    _init_script_re = re.compile('/etc/init.d/[\w\-\.]')
    _list_contents = "dpkg-query -L %s 2>/dev/null"

    def __init__(self, name):
         Pkg.__init__(self, name)

    @property
    def shared_objects(self):
        if self._shared_objects != None:
            return self._shared_objects

        self._shared_objects = []
        contents = self._get_contents()

        for line in contents:
            m = self._so_regex.match(line)
            if m:
                self._shared_objects.append(m.group('so'))
        return self._shared_objects

    @property
    def services(self):
        if self._services != None:
            return self._services

        self._services = []
        contents = self._get_contents()
        # Only supports sysvinit so far:
        for line in contents:
            if self._init_script_re.match(line):
                self._services.append(os.path.basename(line.strip()))
        return self._services


class RedHatDistro(Distro):
    "RPM based distribution"""
    _pkg_re = re.compile(r'(?P<pkg>[\w\-\+]+)-(?P<ver>[\w\.]+)-(?P<rel>[\w\.]+)\.(?P<arch>.+)')

    @classmethod
    def pkg(klass, name):
        return RpmPkg(name)

    @classmethod
    def pkg_by_file(klass, path):
        find_file = subprocess.Popen(["rpm -qf %s 2>/dev/null" % path],
                                      stdout=subprocess.PIPE, shell=True)
        output = find_file.communicate()[0]
        if find_file.returncode:
            return None
        m = klass._pkg_re.match(output.strip())
        if m:
            pkg = m.group('pkg')
        else:
            pkg = output.strip()
        return RpmPkg(pkg)

    @classmethod
    def restart_service(klass, name):
        raise NotImplementedError


class FedoraDistro(RedHatDistro):
    id = 'Fedora'


class RpmPkg(Pkg):
    type = 'RPM'
    _init_script_re = re.compile('/etc/init.d/[\w\-\.]')
    _list_contents = "rpm -ql %s 2>/dev/null"

    def __init__(self, name):
        Pkg.__init__(self, name)

    @property
    def shared_objects(self):
        if self._shared_objects != None:
            return self._shared_objects

        self._shared_objects = []
        contents = self._get_contents()

        for line in contents:
            m = self._so_regex.match(line)
            if m:
                self._shared_objects.append(m.group('so'))
        return self._shared_objects

    @property
    def services(self):
        if self._services != None:
            return self._services

        self._services = []
        contents = self._get_contents()
        # Only supports sysvinit so far:
        for line in contents:
            if self._init_script_re.match(line):
                self._services.append(os.path.basename(line.strip()))
        return self._services


def check_maps(procs, shared_objects):
    restart_procs = {}
    for proc in procs:
        for so in shared_objects:
            if proc.maps(so):
                if restart_procs.has_key(proc.exe):
                    restart_procs[proc.exe] += [ proc ]
                else:
                    restart_procs[proc.exe] = [ proc ]
                continue
    return restart_procs


def get_all_pids():
    processes = []
    paths = glob.glob('/proc/[0-9]*')

    for path in paths:
        p = Process(int(path.rsplit('/')[-1]))
        processes.append(p)

    return processes

def detect_distro():
    id = None

    try:
        import lsb_release
        id = lsb_release.get_distro_information()['ID']
    except ImportError:
        lsb_release = subprocess.Popen(["lsb_release --id -s 2>/dev/null"],
                                         stdout=subprocess.PIPE, shell=True)
        output = lsb_release.communicate()[0]
        if not lsb_release.returncode:
            id = output.strip()

    if id == DebianDistro.id:
        return DebianDistro
    elif id == FedoraDistro.id:
        return FedoraDistro
    else:
        if os.path.exists('/usr/bin/dpkg'):
            logging.warning("Unknown distro but dpkg found, assuming Debian")
            return DebianDistro
        elif os.path.exists('/bin/rpm'):
            logging.warning("Unknown distro but rpm found, assuming Fedora")
            return FedoraDistro
        else:
            return None


def main(argv):
    shared_objects = []

    parser = OptionParser(usage='%prog [options] pkg1 [pkg2 pkg3 pkg4]')
    parser.add_option("--debug", action="store_true", dest="debug", default=False,
                      help="enable debug output")
    parser.add_option("--verbose", action="store_true", dest="verbose", default=False,
                      help="enable verbose output")
    parser.add_option("--restart", action="store_true", dest="restart", default=False,
                      help="Restart services")
    (options, args) = parser.parse_args(argv[1:])

    if options.debug:
        level = logging.DEBUG
    elif options.verbose:
        level = logging.INFO
    else:
        level = logging.WARNING

    logging.basicConfig(level=level,
                        format='%(levelname)s: %(message)s')

    distro = detect_distro()
    if not distro:
        logging.error("Unsupported Distribution")
        return 1
    else:
        logging.debug("Detected distribution: '%s'", distro.id)

    if not args:
        parser.print_help()
        return 1
    else:
        pkgs = [ distro.pkg(arg) for arg in args ]

    # Find shared objects of updated packages
    for pkg in pkgs:
        try:
            shared_objects += pkg.shared_objects
        except PkgError:
            logging.error("Cannot parse contents of %s" % pkg.name)
            return 1
    logging.debug("Found shared objects:")
    map(lambda x: logging.debug("  %s", x), shared_objects)

    # Find processes that map them
    restart_procs = check_maps(get_all_pids(), shared_objects)
    logging.debug("Processes that map them:")
    map(lambda (x, y):  logging.debug("  Exe: %s Pids: %s", x, y), restart_procs.items())

    # Find packages that contain the binaries of these processes
    pkgs = {}
    for proc in restart_procs:
        pkg = distro.pkg_by_file(proc)
        if not pkg:
            logging.warning("No package found for '%s' - restart manually" % proc)
        else:
            if pkgs.has_key(pkg.name):
                pkgs[pkg.name].procs.append(proc)
            else:
                pkg.procs = [ proc ]
                pkgs[pkg.name] = pkg

    logging.info("Packages and binaries:")
    map(lambda x: logging.info("  Pkg: %s, binaries: %s" % (x.name, x.procs)),
        pkgs.values())

    all_services = set()
    try:
        for pkg in pkgs.values():
            services = pkg.services + distro.pkg_services(pkg)
            if not services:
                logging.warning("No service script found in '%s' for '%s' "
                                "- restart manually" % (pkg.name, pkg.procs))
            else:
                all_services = all_services.union(services)
    except NotImplementedError:
        if level > logging.INFO:
            logging.error("Getting Service listing not implemented "
            "for distribution %s - rerun with --verbose to see a list"
            "of binaries and packages to map a shared objects from %s",
            distro.id, args)
            return 1
        else:
            return 0

    if options.restart:
        for service in all_services:
            logging.info("Restarting %s" % service)
            distro.restart_service(service)
    elif all_services:
        print "Services that possibly need to be restarted:"
        for s in all_services:
            print s

    return 0

if __name__ == '__main__':
    sys.exit(main(sys.argv))

# vim:et:ts=4:sw=4:et:sts=4:ai:set list listchars=tab\:»·,trail\:·: