diff options
author | Guido Günther <agx@sigxcpu.org> | 2014-08-05 14:43:14 +0200 |
---|---|---|
committer | Guido Günther <agx@sigxcpu.org> | 2014-08-05 14:43:14 +0200 |
commit | 95620b53bcdf68843cd210306bb7228bfee3239c (patch) | |
tree | 71e1578814515cdc67cfd9fff230d98d4b5fd99f /whatmaps | |
parent | a0aa1dd751453a3557f16912cc5cfe1225eb3253 (diff) | |
parent | 20df31b862f3fbb274a4bb4952a84a53b73238a0 (diff) |
Merge tag 'debian/0.0.8-2' into bpo/wheezy
whatmaps Debian release 0.0.8-2
Diffstat (limited to 'whatmaps')
-rwxr-xr-x | whatmaps/command.py | 184 | ||||
-rw-r--r-- | whatmaps/debiandistro.py | 22 | ||||
-rw-r--r-- | whatmaps/distro.py | 66 | ||||
-rw-r--r-- | whatmaps/redhatdistro.py | 1 | ||||
-rw-r--r-- | whatmaps/systemd.py | 41 |
5 files changed, 219 insertions, 95 deletions
diff --git a/whatmaps/command.py b/whatmaps/command.py index 3225f54..7690ef8 100755 --- a/whatmaps/command.py +++ b/whatmaps/command.py @@ -18,27 +18,17 @@ from __future__ import print_function +import errno import glob import os import logging -import re -import string -import subprocess import sys -import errno from optparse import OptionParser -try: - import lsb_release -except ImportError: - lsb_release = None from . process import Process -from . debiandistro import DebianDistro -from . redhatdistro import FedoraDistro -from . pkg import Pkg, PkgError -from . debianpkg import DebianPkg -from . rpmpkg import RpmPkg - +from . distro import Distro +from . pkg import PkgError +from . systemd import Systemd def check_maps(procs, shared_objects): restart_procs = {} @@ -64,38 +54,6 @@ def get_all_pids(): return processes -def detect_distro(): - id = None - - if lsb_release: - id = lsb_release.get_distro_information()['ID'] - else: - try: - lsb_cmd = subprocess.Popen(['lsb_release', '--id', '-s'], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE) - output = lsb_cmd.communicate()[0] - if not lsb_cmd.returncode: - id = output.strip() - except OSError: - # id is None in this case - pass - - 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 write_cmd_file(services, cmd_file, distro): "Write out commands needed to restart the services to a file" out = open(cmd_file, 'w') @@ -107,8 +65,67 @@ def write_cmd_file(services, cmd_file, distro): os.chmod(cmd_file, 0o755) +def find_pkgs(procs, distro): + """ + Find packages that contain the binaries of the given processes + """ + pkgs = {} + for proc in procs: + pkg = distro.pkg_by_file(proc) + if not pkg: + logging.warning("No package found for '%s' - restart manually" % proc) + else: + if pkg.name in pkgs: + pkgs[pkg.name].procs.append(proc) + else: + pkg.procs = [ proc ] + pkgs[pkg.name] = pkg + + logging.info("Packages that ship the affected binaries:") + for pkg in pkgs.values(): + logging.info(" Pkg: %s, binaries: %s" % (pkg.name, pkg.procs)) + + return pkgs + + +def find_services(pkgs, distro): + """ + Determine the services in pkgs honoring distro specific mappings + and blacklists + """ + all_services = set() + + for pkg in pkgs.values(): + services = set(pkg.services + distro.pkg_services(pkg)) + services -= set(distro.pkg_service_blacklist(pkg)) + if not services: + logging.warning("No service script found in '%s' for '%s' " + "- restart manually" % (pkg.name, pkg.procs)) + else: + all_services.update(services) + all_services -= distro.service_blacklist + return all_services + + +def find_systemd_units(procmap, distro): + """Find systemd units that contain the given processes""" + units = set() + + for dummy, procs in procmap.items(): + for proc in procs: + unit = Systemd.process_to_unit(proc) + if not unit: + logging.warning("No systemd unit found for '%s'" + "- restart manually" % proc.exe) + else: + units.add(unit) + units -= set([ service + '.service' for service in distro.service_blacklist ]) + return units + + def main(argv): shared_objects = [] + services = None parser = OptionParser(usage='%prog [options] pkg1 [pkg2 pkg3 pkg4]') parser.add_option("--debug", action="store_true", dest="debug", @@ -134,7 +151,7 @@ def main(argv): logging.basicConfig(level=level, format='%(levelname)s: %(message)s') - distro = detect_distro() + distro = Distro.detect() if not distro: logging.error("Unsupported Distribution") return 1 @@ -169,59 +186,50 @@ def main(argv): logging.debug(" %s", so) # Find processes that map them - restart_procs = check_maps(get_all_pids(), shared_objects) + try: + restart_procs = check_maps(get_all_pids(), shared_objects) + except IOError as e: + if e.errno == errno.EACCES: + logging.error("Can't open process maps in '/proc/<pid>/maps', are you root?") + return 1 + else: + raise logging.debug("Processes that map them:") for exe, pids in restart_procs.items(): logging.debug(" Exe: %s Pids: %s", exe, pids), - # 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 pkg.name in pkgs: - pkgs[pkg.name].procs.append(proc) - else: - pkg.procs = [ proc ] - pkgs[pkg.name] = pkg - - logging.info("Packages that ship the affected binaries:") - for pkg in pkgs.values(): - logging.info(" Pkg: %s, binaries: %s" % (pkg.name, pkg.procs)) + if Systemd.is_running(): + logging.debug("Detected Systemd") + services = find_systemd_units(restart_procs, distro) + else: + # Find the packages that contain the binaries the processes are + # executing + pkgs = find_pkgs(restart_procs, distro) - all_services = set() - try: - for pkg in pkgs.values(): - services = set(pkg.services + distro.pkg_services(pkg)) - services -= set(distro.pkg_service_blacklist(pkg)) - if not services: - logging.warning("No service script found in '%s' for '%s' " - "- restart manually" % (pkg.name, pkg.procs)) + # Find the services in these packages honoring distro specific + # mappings and blacklists + try: + services = find_services(pkgs, distro) + 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 that map a shared objects from %s", + distro.id, args) + return 1 else: - all_services.update(services) - all_services -= distro.service_blacklist - 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 + return 0 if options.restart: - if options.print_cmds and all_services: - write_cmd_file(all_services, options.print_cmds, distro) + if options.print_cmds and services: + write_cmd_file(services, options.print_cmds, distro) else: - for service in all_services: + for service in services: logging.info("Restarting %s" % service) distro.restart_service(service) - elif all_services: + elif services: print("Services that possibly need to be restarted:") - for s in all_services: + for s in services: print(s) return 0 diff --git a/whatmaps/debiandistro.py b/whatmaps/debiandistro.py index 4a3d0db..9294c9f 100644 --- a/whatmaps/debiandistro.py +++ b/whatmaps/debiandistro.py @@ -26,16 +26,18 @@ except ImportError: lsb_release = None import logging -import string +import os import subprocess import sys +import string -from . distro import Distro +import whatmaps.distro from . debianpkg import DebianPkg from . pkg import PkgError +from . systemd import Systemd -class DebianDistro(Distro): - "Debian (dpkg) based distribution""" +class DebianDistro(whatmaps.distro.Distro): + "Debian (dpkg) based distribution" id = 'Debian' _pkg_services = { 'apache2-mpm-worker': [ 'apache2' ], @@ -72,10 +74,20 @@ class DebianDistro(Distro): return DebianPkg(pkg) @classmethod - def restart_service_cmd(klass, name): + def restart_service_cmd(klass, service): + """The command that should be used to start a service""" + if Systemd.is_running() and service.endswith('.service'): + name = service[:-len('.service')] + else: + name = service return ['invoke-rc.d', name, 'restart'] @classmethod + def is_service_installed(klass, name): + """Whether the system has this service""" + return os.path.exists('/etc/init.d/%s' % name) + + @classmethod def has_apt(klass): return True diff --git a/whatmaps/distro.py b/whatmaps/distro.py index e4f417f..f0f08eb 100644 --- a/whatmaps/distro.py +++ b/whatmaps/distro.py @@ -15,12 +15,28 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # +import logging +import os import subprocess + +try: + import lsb_release +except ImportError: + lsb_release = None + class Distro(object): """ A distribution + @cvar id: distro id as returned by lsb-release + + @cvar service_blacklist: services that should never be restarted + @cvar _pkg_services: A C{dict} that maps packages to services. In + case we find binaries that match a key in this hash restart + the services listed in values. + @cvar _pkg_service_blacklist: if we find binaries in the package + listed as key don't restart services listed in values """ id = None service_blacklist = set() @@ -49,12 +65,18 @@ class Distro(object): subprocess.call(klass.restart_service_cmd(service)) @classmethod + def is_service_installed(klass, service): + """Check wether a service exists on the system""" + return True + + @classmethod def pkg_services(klass, pkg): """ List of services that package pkg needs restarted that aren't part of pkg itself """ - return klass._pkg_services.get(pkg.name, []) + return [ s for s in klass._pkg_services.get(pkg.name, []) + if klass.is_service_installed(s) ] @classmethod def pkg_service_blacklist(klass, pkg): @@ -68,3 +90,45 @@ class Distro(object): def has_apt(klass): """Does the distribution use apt""" return False + + @staticmethod + def detect(): + return detect() + +import whatmaps.debiandistro +import whatmaps.redhatdistro + +def detect(): + """ + Detect the distribution we run on. Returns C{None} if the + distribution is unknown. + """ + id = None + + if lsb_release: + id = lsb_release.get_distro_information()['ID'] + else: + try: + lsb_cmd = subprocess.Popen(['lsb_release', '--id', '-s'], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + output = lsb_cmd.communicate()[0] + if not lsb_cmd.returncode: + id = output.strip() + except OSError: + # id is None in this case + pass + + if id == whatmaps.debiandistro.DebianDistro.id: + return whatmaps.debiandistro.DebianDistro + elif id == whatmaps.redhatdistro.FedoraDistro.id: + return whatmaps.redhatdistro.FedoraDistro + else: + if os.path.exists('/usr/bin/dpkg'): + logging.warning("Unknown distro but dpkg found, assuming Debian") + return whatmaps.debiandistro.DebianDistro + elif os.path.exists('/bin/rpm'): + logging.warning("Unknown distro but rpm found, assuming Fedora") + return whatmaps.debiandistro.FedoraDistro + else: + return None diff --git a/whatmaps/redhatdistro.py b/whatmaps/redhatdistro.py index 4d9f5cf..9300648 100644 --- a/whatmaps/redhatdistro.py +++ b/whatmaps/redhatdistro.py @@ -20,7 +20,6 @@ import re import subprocess from . distro import Distro -from . pkg import PkgError from . rpmpkg import RpmPkg class RedHatDistro(Distro): diff --git a/whatmaps/systemd.py b/whatmaps/systemd.py new file mode 100644 index 0000000..add6d0e --- /dev/null +++ b/whatmaps/systemd.py @@ -0,0 +1,41 @@ +# vim: set fileencoding=utf-8 : +# +# (C) 2014 Guido Günther <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 os +import subprocess + + +class Systemd(object): + """Systemd init system""" + + def __init__(self): + if not self.is_running(): + raise ValueError("Systemd not running") + + @staticmethod + def is_running(): + return os.path.exists("/run/systemd/system") + + @staticmethod + def process_to_unit(process): + cmd = ['systemctl', 'status', "%d" % process.pid] + systemctl_status = subprocess.Popen(cmd, stdout=subprocess.PIPE) + output = systemctl_status.communicate()[0] + if systemctl_status.returncode: + return None + else: + return output.split()[0] |