summaryrefslogtreecommitdiffstats
path: root/src/lib/Bcfg2/Client/Tools
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/Bcfg2/Client/Tools')
-rw-r--r--src/lib/Bcfg2/Client/Tools/APK.py7
-rw-r--r--src/lib/Bcfg2/Client/Tools/APT.py158
-rw-r--r--src/lib/Bcfg2/Client/Tools/Action.py48
-rw-r--r--src/lib/Bcfg2/Client/Tools/Blast.py4
-rw-r--r--src/lib/Bcfg2/Client/Tools/BundleDeps.py34
-rw-r--r--src/lib/Bcfg2/Client/Tools/Chkconfig.py13
-rw-r--r--src/lib/Bcfg2/Client/Tools/DebInit.py9
-rw-r--r--src/lib/Bcfg2/Client/Tools/FreeBSDInit.py139
-rw-r--r--src/lib/Bcfg2/Client/Tools/HomeBrew.py54
-rw-r--r--src/lib/Bcfg2/Client/Tools/IPS.py5
-rw-r--r--src/lib/Bcfg2/Client/Tools/MacPorts.py5
-rw-r--r--src/lib/Bcfg2/Client/Tools/OpenCSW.py4
-rw-r--r--src/lib/Bcfg2/Client/Tools/POSIX/Augeas.py6
-rw-r--r--src/lib/Bcfg2/Client/Tools/POSIX/Device.py2
-rw-r--r--src/lib/Bcfg2/Client/Tools/POSIX/File.py64
-rw-r--r--src/lib/Bcfg2/Client/Tools/POSIX/Nonexistent.py4
-rw-r--r--src/lib/Bcfg2/Client/Tools/POSIX/__init__.py53
-rw-r--r--src/lib/Bcfg2/Client/Tools/POSIX/base.py58
-rw-r--r--src/lib/Bcfg2/Client/Tools/POSIXUsers.py64
-rw-r--r--src/lib/Bcfg2/Client/Tools/Pacman.py9
-rw-r--r--src/lib/Bcfg2/Client/Tools/Pkgng.py227
-rw-r--r--src/lib/Bcfg2/Client/Tools/Portage.py22
-rw-r--r--src/lib/Bcfg2/Client/Tools/RPM.py1952
-rw-r--r--src/lib/Bcfg2/Client/Tools/RPMng.py9
-rw-r--r--src/lib/Bcfg2/Client/Tools/RcUpdate.py4
-rw-r--r--src/lib/Bcfg2/Client/Tools/SELinux.py41
-rw-r--r--src/lib/Bcfg2/Client/Tools/SYSV.py10
-rw-r--r--src/lib/Bcfg2/Client/Tools/Systemd.py83
-rw-r--r--src/lib/Bcfg2/Client/Tools/VCS.py12
-rw-r--r--src/lib/Bcfg2/Client/Tools/YUM.py163
-rw-r--r--src/lib/Bcfg2/Client/Tools/YUM24.py399
-rw-r--r--src/lib/Bcfg2/Client/Tools/YUMng.py9
-rw-r--r--src/lib/Bcfg2/Client/Tools/__init__.py165
-rw-r--r--src/lib/Bcfg2/Client/Tools/launchd.py10
-rwxr-xr-xsrc/lib/Bcfg2/Client/Tools/rpmtools.py1091
35 files changed, 2574 insertions, 2363 deletions
diff --git a/src/lib/Bcfg2/Client/Tools/APK.py b/src/lib/Bcfg2/Client/Tools/APK.py
index eb70fa676..7313f6fcc 100644
--- a/src/lib/Bcfg2/Client/Tools/APK.py
+++ b/src/lib/Bcfg2/Client/Tools/APK.py
@@ -12,11 +12,6 @@ class APK(Bcfg2.Client.Tools.PkgTool):
pkgtype = 'apk'
pkgtool = ("/sbin/apk add %s", ("%s", ["name"]))
- def __init__(self, logger, setup, config):
- Bcfg2.Client.Tools.PkgTool.__init__(self, logger, setup, config)
- self.installed = {}
- self.RefreshPackages()
-
def RefreshPackages(self):
"""Refresh memory hashes of packages."""
names = self.cmd.run("/sbin/apk info").stdout.splitlines()
@@ -38,8 +33,6 @@ class APK(Bcfg2.Client.Tools.PkgTool):
if entry.attrib['name'] in self.installed:
if entry.attrib['version'] in \
['auto', self.installed[entry.attrib['name']]]:
- # if (not self.setup['quick'] and
- # entry.get('verify', 'true') == 'true'):
# FIXME: Does APK have any sort of verification mechanism?
return True
else:
diff --git a/src/lib/Bcfg2/Client/Tools/APT.py b/src/lib/Bcfg2/Client/Tools/APT.py
index 1d9b0dd70..abc76ef1c 100644
--- a/src/lib/Bcfg2/Client/Tools/APT.py
+++ b/src/lib/Bcfg2/Client/Tools/APT.py
@@ -5,28 +5,36 @@ import sys
import apt.cache
+import Bcfg2.Options
import Bcfg2.Client.Tools
class APT(Bcfg2.Client.Tools.Tool):
- """The Debian toolset implements package and service operations and
- inherits the rest from Toolset.Toolset.
+ """The Debian toolset implements package and service operations
+ and inherits the rest from Tools.Tool."""
+
+ options = Bcfg2.Client.Tools.Tool.options + [
+ Bcfg2.Options.PathOption(
+ cf=('APT', 'install_path'),
+ default='/usr', dest='apt_install_path',
+ help='Apt tools install path'),
+ Bcfg2.Options.PathOption(
+ cf=('APT', 'var_path'), default='/var', dest='apt_var_path',
+ help='Apt tools var path'),
+ Bcfg2.Options.PathOption(
+ cf=('APT', 'etc_path'), default='/etc', dest='apt_etc_path',
+ help='System etc path')]
- """
- name = 'APT'
__execs__ = []
__handles__ = [('Package', 'deb'), ('Path', 'ignore')]
__req__ = {'Package': ['name', 'version'], 'Path': ['type']}
- def __init__(self, logger, setup, config):
- Bcfg2.Client.Tools.Tool.__init__(self, logger, setup, config)
+ def __init__(self, config):
+ Bcfg2.Client.Tools.Tool.__init__(self, config)
- self.install_path = setup.get('apt_install_path', '/usr')
- self.var_path = setup.get('apt_var_path', '/var')
- self.etc_path = setup.get('apt_etc_path', '/etc')
- self.debsums = '%s/bin/debsums' % self.install_path
- self.aptget = '%s/bin/apt-get' % self.install_path
- self.dpkg = '%s/bin/dpkg' % self.install_path
+ self.debsums = '%s/bin/debsums' % Bcfg2.Options.setup.apt_install_path
+ self.aptget = '%s/bin/apt-get' % Bcfg2.Options.setup.apt_install_path
+ self.dpkg = '%s/bin/dpkg' % Bcfg2.Options.setup.apt_install_path
self.__execs__ = [self.debsums, self.aptget, self.dpkg]
path_entries = os.environ['PATH'].split(':')
@@ -38,7 +46,7 @@ class APT(Bcfg2.Client.Tools.Tool):
'-o DPkg::Options::=--force-confmiss ' + \
'--reinstall ' + \
'--force-yes '
- if not self.setup['debug']:
+ if not Bcfg2.Options.setup.debug:
self.pkgcmd += '-q=2 '
self.pkgcmd += '-y install %s'
self.ignores = [entry.get('name') for struct in config
@@ -46,22 +54,25 @@ class APT(Bcfg2.Client.Tools.Tool):
if entry.tag == 'Path' and
entry.get('type') == 'ignore']
self.__important__ = self.__important__ + [
- "%s/cache/debconf/config.dat" % self.var_path,
- "%s/cache/debconf/templates.dat" % self.var_path,
+ "%s/cache/debconf/config.dat" % Bcfg2.Options.setup.apt_var_path,
+ "%s/cache/debconf/templates.dat" %
+ Bcfg2.Options.setup.apt_var_path,
'/etc/passwd', '/etc/group',
- '%s/apt/apt.conf' % self.etc_path,
- '%s/dpkg/dpkg.cfg' % self.etc_path] + \
- [entry.get('name') for struct in config for entry in struct
+ '%s/apt/apt.conf' % Bcfg2.Options.setup.apt_etc_path,
+ '%s/dpkg/dpkg.cfg' % Bcfg2.Options.setup.apt_etc_path] + \
+ [entry.get('name') for struct in config
+ for entry in struct
if (entry.tag == 'Path' and
entry.get('name').startswith(
- '%s/apt/sources.list' % self.etc_path))]
+ '%s/apt/sources.list' %
+ Bcfg2.Options.setup.apt_etc_path))]
self.nonexistent = [entry.get('name') for struct in config
for entry in struct
if (entry.tag == 'Path' and
entry.get('type') == 'nonexistent')]
os.environ["DEBIAN_FRONTEND"] = 'noninteractive'
self.actions = {}
- if self.setup['kevlar'] and not self.setup['dryrun']:
+ if Bcfg2.Options.setup.kevlar and not Bcfg2.Options.setup.dry_run:
self.cmd.run("%s --force-confold --configure --pending" %
self.dpkg)
self.cmd.run("%s clean" % self.aptget)
@@ -77,22 +88,14 @@ class APT(Bcfg2.Client.Tools.Tool):
err = sys.exc_info()[1]
self.logger.info("Failed to update APT cache: %s" % err)
self.pkg_cache = apt.cache.Cache()
- if 'req_reinstall_pkgs' in dir(self.pkg_cache):
- self._newapi = True
- else:
- self._newapi = False
def FindExtra(self):
"""Find extra packages."""
packages = [entry.get('name') for entry in self.getSupportedEntries()]
- if self._newapi:
- extras = [(p.name, p.installed.version) for p in self.pkg_cache
- if p.is_installed and p.name not in packages]
- else:
- extras = [(p.name, p.installedVersion) for p in self.pkg_cache
- if p.isInstalled and p.name not in packages]
- return [Bcfg2.Client.XML.Element('Package', name=name,
- type='deb', version=version)
+ extras = [(p.name, p.installed.version) for p in self.pkg_cache
+ if p.is_installed and p.name not in packages]
+ return [Bcfg2.Client.XML.Element('Package', name=name, type='deb',
+ current_version=version)
for (name, version) in extras]
def VerifyDebsums(self, entry, modlist):
@@ -155,34 +158,17 @@ class APT(Bcfg2.Client.Tools.Tool):
(entry.attrib['name']))
return False
pkgname = entry.get('name')
- if self.pkg_cache.has_key(pkgname): # noqa
- if self._newapi:
- is_installed = self.pkg_cache[pkgname].is_installed
- else:
- is_installed = self.pkg_cache[pkgname].isInstalled
- if not self.pkg_cache.has_key(pkgname) or not is_installed: # noqa
+ if pkgname not in self.pkg_cache or \
+ not self.pkg_cache[pkgname].is_installed:
self.logger.info("Package %s not installed" % (entry.get('name')))
entry.set('current_exists', 'false')
return False
pkg = self.pkg_cache[pkgname]
- if self._newapi:
- installed_version = pkg.installed.version
- candidate_version = pkg.candidate.version
- else:
- installed_version = pkg.installedVersion
- candidate_version = pkg.candidateVersion
+ installed_version = pkg.installed.version
if entry.get('version') == 'auto':
- # pylint: disable=W0212
- if self._newapi:
- is_upgradable = self.pkg_cache._depcache.is_upgradable(
- pkg._pkg)
- else:
- is_upgradable = self.pkg_cache._depcache.IsUpgradable(
- pkg._pkg)
- # pylint: enable=W0212
- if is_upgradable:
- desired_version = candidate_version
+ if pkg.is_upgradable:
+ desired_version = pkg.candidate.version
else:
desired_version = installed_version
elif entry.get('version') == 'any':
@@ -197,7 +183,7 @@ class APT(Bcfg2.Client.Tools.Tool):
return False
else:
# version matches
- if not self.setup['quick'] \
+ if not Bcfg2.Options.setup.quick \
and entry.get('verify', 'true') == 'true' \
and checksums:
pkgsums = self.VerifyDebsums(entry, modlist)
@@ -212,68 +198,40 @@ class APT(Bcfg2.Client.Tools.Tool):
self.logger.info('Removing packages:')
self.logger.info(pkgnames)
for pkg in pkgnames.split(" "):
- try:
- if self._newapi:
- self.pkg_cache[pkg].mark_delete(purge=True)
- else:
- self.pkg_cache[pkg].markDelete(purge=True)
- except: # pylint: disable=W0702
- if self._newapi:
- self.pkg_cache[pkg].mark_delete()
- else:
- self.pkg_cache[pkg].markDelete()
- try:
- self.pkg_cache.commit()
- except SystemExit:
- # thank you python-apt 0.6
- pass
+ self.pkg_cache[pkg].mark_delete(purge=True)
+ self.pkg_cache.commit()
self.pkg_cache = apt.cache.Cache()
self.modified += packages
self.extra = self.FindExtra()
- def Install(self, packages, states):
+ def Install(self, packages):
# it looks like you can't install arbitrary versions of software
# out of the pkg cache, we will still need to call apt-get
ipkgs = []
bad_pkgs = []
for pkg in packages:
- if not self.pkg_cache.has_key(pkg.get('name')): # noqa
+ pkgname = pkg.get('name')
+ if pkgname not in self.pkg_cache:
self.logger.error("APT has no information about package %s"
- % (pkg.get('name')))
+ % pkgname)
continue
if pkg.get('version') in ['auto', 'any']:
- if self._newapi:
- try:
- ipkgs.append("%s=%s" % (
- pkg.get('name'),
- self.pkg_cache[pkg.get('name')].candidate.version))
- except AttributeError:
- self.logger.error("Failed to find %s in apt package "
- "cache" % pkg.get('name'))
- continue
- else:
+ try:
ipkgs.append("%s=%s" % (
- pkg.get('name'),
- self.pkg_cache[pkg.get('name')].candidateVersion))
+ pkgname,
+ self.pkg_cache[pkgname].candidate.version))
+ except AttributeError:
+ self.logger.error("Failed to find %s in apt package "
+ "cache" % pkgname)
continue
- # pylint: disable=W0212
- if self._newapi:
- avail_vers = [
- x.ver_str for x in
- self.pkg_cache[pkg.get('name')]._pkg.version_list]
- else:
- avail_vers = [
- x.VerStr for x in
- self.pkg_cache[pkg.get('name')]._pkg.VersionList]
- # pylint: enable=W0212
+ avail_vers = self.pkg_cache[pkgname].versions.keys()
if pkg.get('version') in avail_vers:
- ipkgs.append("%s=%s" % (pkg.get('name'), pkg.get('version')))
+ ipkgs.append("%s=%s" % (pkgname, pkg.get('version')))
continue
else:
self.logger.error("Package %s: desired version %s not in %s"
- % (pkg.get('name'), pkg.get('version'),
- avail_vers))
- bad_pkgs.append(pkg.get('name'))
+ % (pkgname, pkg.get('version'), avail_vers))
+ bad_pkgs.append(pkgname)
if bad_pkgs:
self.logger.error("Cannot find correct versions of packages:")
self.logger.error(bad_pkgs)
@@ -283,10 +241,12 @@ class APT(Bcfg2.Client.Tools.Tool):
self.logger.error("APT command failed")
self.pkg_cache = apt.cache.Cache()
self.extra = self.FindExtra()
+ states = dict()
for package in packages:
states[package] = self.VerifyPackage(package, [], checksums=False)
if states[package]:
self.modified.append(package)
+ return states
def VerifyPath(self, entry, _): # pylint: disable=W0613
"""Do nothing here since we only verify Path type=ignore."""
diff --git a/src/lib/Bcfg2/Client/Tools/Action.py b/src/lib/Bcfg2/Client/Tools/Action.py
index 1edf4609b..ca0502b75 100644
--- a/src/lib/Bcfg2/Client/Tools/Action.py
+++ b/src/lib/Bcfg2/Client/Tools/Action.py
@@ -1,18 +1,14 @@
"""Action driver"""
-import os
-import sys
-import select
import Bcfg2.Client.Tools
-from Bcfg2.Compat import input # pylint: disable=W0622
+from Bcfg2.Utils import safe_input
class Action(Bcfg2.Client.Tools.Tool):
"""Implement Actions"""
name = 'Action'
- __handles__ = [('PostInstall', None), ('Action', None)]
- __req__ = {'PostInstall': ['name'],
- 'Action': ['name', 'timing', 'when', 'command', 'status']}
+ __handles__ = [('Action', None)]
+ __req__ = {'Action': ['name', 'timing', 'when', 'command', 'status']}
def RunAction(self, entry):
"""This method handles command execution and status return."""
@@ -22,19 +18,15 @@ class Action(Bcfg2.Client.Tools.Tool):
shell = True
shell_string = '(in shell) '
- if not self.setup['dryrun']:
- if self.setup['interactive']:
+ if not Bcfg2.Options.setup.dry_run:
+ if Bcfg2.Options.setup.interactive:
prompt = ('Run Action %s%s, %s: (y/N): ' %
(shell_string, entry.get('name'),
entry.get('command')))
- # flush input buffer
- while len(select.select([sys.stdin.fileno()], [], [],
- 0.0)[0]) > 0:
- os.read(sys.stdin.fileno(), 4096)
- ans = input(prompt)
+ ans = safe_input(prompt)
if ans not in ['y', 'Y']:
return False
- if self.setup['servicemode'] == 'build':
+ if Bcfg2.Options.setup.service_mode == 'build':
if entry.get('build', 'true') == 'false':
self.logger.debug("Action: Deferring execution of %s due "
"to build mode" % entry.get('command'))
@@ -55,39 +47,29 @@ class Action(Bcfg2.Client.Tools.Tool):
"""Actions always verify true."""
return True
- def VerifyPostInstall(self, dummy, _):
- """Actions always verify true."""
- return True
-
def InstallAction(self, entry):
"""Run actions as pre-checks for bundle installation."""
if entry.get('timing') != 'post':
return self.RunAction(entry)
return True
- def InstallPostInstall(self, entry):
- """ Install a deprecated PostInstall entry """
- self.logger.warning("Installing deprecated PostInstall entry %s" %
- entry.get("name"))
- return self.InstallAction(entry)
-
- def BundleUpdated(self, bundle, states):
+ def BundleUpdated(self, bundle):
"""Run postinstalls when bundles have been updated."""
- for postinst in bundle.findall("PostInstall"):
- if not self._install_allowed(postinst):
- continue
- self.cmd.run(postinst.get('name'))
+ states = dict()
for action in bundle.findall("Action"):
if action.get('timing') in ['post', 'both']:
if not self._install_allowed(action):
continue
states[action] = self.RunAction(action)
+ return states
- def BundleNotUpdated(self, bundle, states):
+ def BundleNotUpdated(self, bundle):
"""Run Actions when bundles have not been updated."""
+ states = dict()
for action in bundle.findall("Action"):
- if action.get('timing') in ['post', 'both'] and \
- action.get('when') != 'modified':
+ if (action.get('timing') in ['post', 'both'] and
+ action.get('when') != 'modified'):
if not self._install_allowed(action):
continue
states[action] = self.RunAction(action)
+ return states
diff --git a/src/lib/Bcfg2/Client/Tools/Blast.py b/src/lib/Bcfg2/Client/Tools/Blast.py
index 2627c42fe..fd594b4f4 100644
--- a/src/lib/Bcfg2/Client/Tools/Blast.py
+++ b/src/lib/Bcfg2/Client/Tools/Blast.py
@@ -13,9 +13,9 @@ class Blast(Bcfg2.Client.Tools.SYSV.SYSV):
__handles__ = [('Package', 'blast')]
__req__ = {'Package': ['name', 'version', 'bname']}
- def __init__(self, logger, setup, config):
+ def __init__(self, config):
# dont use the sysv constructor
- Bcfg2.Client.Tools.PkgTool.__init__(self, logger, setup, config)
+ Bcfg2.Client.Tools.PkgTool.__init__(self, config)
noaskfile = tempfile.NamedTemporaryFile()
self.noaskname = noaskfile.name
try:
diff --git a/src/lib/Bcfg2/Client/Tools/BundleDeps.py b/src/lib/Bcfg2/Client/Tools/BundleDeps.py
new file mode 100644
index 000000000..aaa090633
--- /dev/null
+++ b/src/lib/Bcfg2/Client/Tools/BundleDeps.py
@@ -0,0 +1,34 @@
+""" Bundle dependency support """
+
+import Bcfg2.Client.Tools
+
+
+class BundleDeps(Bcfg2.Client.Tools.Tool):
+ """Bundle dependency helper for Bcfg2. It handles Bundle tags inside the
+ bundles that references the required other bundles that should change the
+ modification status if the referenced bundles is modified."""
+
+ name = 'Bundle'
+ __handles__ = [('Bundle', None)]
+ __req__ = {'Bundle': ['name']}
+
+ def InstallBundle(self, _):
+ """Simple no-op because we only need the BundleUpdated hook."""
+ return dict()
+
+ def VerifyBundle(self, entry, _): # pylint: disable=W0613
+ """Simple no-op because we only need the BundleUpdated hook."""
+ return True
+
+ def BundleUpdated(self, entry):
+ """This handles the dependencies on this bundle. It searches all
+ Bundle tags in other bundles that references the current bundle name
+ and marks those tags as modified to trigger the modification hook on
+ the other bundles."""
+
+ bundle_name = entry.get('name')
+ for bundle in self.config.findall('./Bundle/Bundle'):
+ if bundle.get('name') == bundle_name and \
+ bundle not in self.modified:
+ self.modified.append(bundle)
+ return dict()
diff --git a/src/lib/Bcfg2/Client/Tools/Chkconfig.py b/src/lib/Bcfg2/Client/Tools/Chkconfig.py
index 4833f3f68..fab142a7c 100644
--- a/src/lib/Bcfg2/Client/Tools/Chkconfig.py
+++ b/src/lib/Bcfg2/Client/Tools/Chkconfig.py
@@ -3,7 +3,6 @@
"""This is chkconfig support."""
import os
-
import Bcfg2.Client.Tools
import Bcfg2.Client.XML
@@ -96,15 +95,15 @@ class Chkconfig(Bcfg2.Client.Tools.SvcTool):
bootcmd = '/sbin/chkconfig %s %s' % (entry.get('name'),
bootstatus)
bootcmdrv = self.cmd.run(bootcmd).success
- if self.setup['servicemode'] == 'disabled':
+ if Bcfg2.Options.setup.servicemode == 'disabled':
# 'disabled' means we don't attempt to modify running svcs
return bootcmdrv
- buildmode = self.setup['servicemode'] == 'build'
- if (entry.get('status') == 'on' and not buildmode) and \
- entry.get('current_status') == 'off':
+ buildmode = Bcfg2.Options.setup.servicemode == 'build'
+ if ((entry.get('status') == 'on' and not buildmode) and
+ entry.get('current_status') == 'off'):
svccmdrv = self.start_service(entry)
- elif (entry.get('status') == 'off' or buildmode) and \
- entry.get('current_status') == 'on':
+ elif ((entry.get('status') == 'off' or buildmode) and
+ entry.get('current_status') == 'on'):
svccmdrv = self.stop_service(entry)
else:
svccmdrv = True # ignore status attribute
diff --git a/src/lib/Bcfg2/Client/Tools/DebInit.py b/src/lib/Bcfg2/Client/Tools/DebInit.py
index b544e44d4..53e5e7ec6 100644
--- a/src/lib/Bcfg2/Client/Tools/DebInit.py
+++ b/src/lib/Bcfg2/Client/Tools/DebInit.py
@@ -3,6 +3,7 @@
import glob
import os
import re
+import Bcfg2.Options
import Bcfg2.Client.Tools
# Debian squeeze and beyond uses a dependecy based boot sequence
@@ -33,8 +34,8 @@ class DebInit(Bcfg2.Client.Tools.SvcTool):
if entry.get('sequence'):
if (deb_version in DEBIAN_OLD_STYLE_BOOT_SEQUENCE or
- deb_version.startswith('5') or
- os.path.exists('/etc/init.d/.legacy-bootordering')):
+ deb_version.startswith('5') or
+ os.path.exists('/etc/init.d/.legacy-bootordering')):
start_sequence = int(entry.get('sequence'))
kill_sequence = 100 - start_sequence
else:
@@ -137,10 +138,10 @@ class DebInit(Bcfg2.Client.Tools.SvcTool):
bootcmd = '/usr/sbin/update-rc.d -f %s remove' % \
entry.get('name')
bootcmdrv = self.cmd.run(bootcmd)
- if self.setup['servicemode'] == 'disabled':
+ if Bcfg2.Options.setup.service_mode == 'disabled':
# 'disabled' means we don't attempt to modify running svcs
return bootcmdrv and seqcmdrv
- buildmode = self.setup['servicemode'] == 'build'
+ buildmode = Bcfg2.Options.setup.service_mode == 'build'
if (entry.get('status') == 'on' and not buildmode) and \
entry.get('current_status') == 'off':
svccmdrv = self.start_service(entry)
diff --git a/src/lib/Bcfg2/Client/Tools/FreeBSDInit.py b/src/lib/Bcfg2/Client/Tools/FreeBSDInit.py
index 917d3ccdb..7c25e6804 100644
--- a/src/lib/Bcfg2/Client/Tools/FreeBSDInit.py
+++ b/src/lib/Bcfg2/Client/Tools/FreeBSDInit.py
@@ -1,27 +1,142 @@
"""FreeBSD Init Support for Bcfg2."""
-__revision__ = '$Rev$'
-
-# TODO
-# - hardcoded path to ports rc.d
-# - doesn't know about /etc/rc.d/
import os
+import re
+import Bcfg2.Options
import Bcfg2.Client.Tools
class FreeBSDInit(Bcfg2.Client.Tools.SvcTool):
"""FreeBSD service support for Bcfg2."""
name = 'FreeBSDInit'
+ __execs__ = ['/usr/sbin/service', '/usr/sbin/sysrc']
__handles__ = [('Service', 'freebsd')]
__req__ = {'Service': ['name', 'status']}
+ rcvar_re = re.compile(r'^(?P<var>[a-z_]+_enable)="[A-Z]+"$')
- def __init__(self, logger, cfg, setup):
- Bcfg2.Client.Tools.SvcTool.__init__(self, logger, cfg, setup)
- if os.uname()[0] != 'FreeBSD':
- raise Bcfg2.Client.Tools.ToolInstantiationError
+ def get_svc_command(self, service, action):
+ return '/usr/sbin/service %s %s' % (service.get('name'), action)
- def VerifyService(self, entry, _):
+ def verify_bootstatus(self, entry, bootstatus):
+ """Verify bootstatus for entry."""
+ cmd = self.get_svc_command(entry, 'enabled')
+ current_bootstatus = bool(self.cmd.run(cmd))
+
+ if bootstatus == 'off':
+ if current_bootstatus:
+ entry.set('current_bootstatus', 'on')
+ return False
+ return True
+ elif not current_bootstatus:
+ entry.set('current_bootstatus', 'off')
+ return False
return True
- def get_svc_command(self, service, action):
- return "/usr/local/etc/rc.d/%s %s" % (service.get('name'), action)
+ def check_service(self, entry):
+ # use 'onestatus' to enable status reporting for disabled services
+ cmd = self.get_svc_command(entry, 'onestatus')
+ return bool(self.cmd.run(cmd))
+
+ def stop_service(self, service):
+ # use 'onestop' to enable stopping of disabled services
+ self.logger.debug('Stopping service %s' % service.get('name'))
+ return self.cmd.run(self.get_svc_command(service, 'onestop'))
+
+ def VerifyService(self, entry, _):
+ """Verify Service status for entry."""
+ entry.set('target_status', entry.get('status')) # for reporting
+ bootstatus = self.get_bootstatus(entry)
+ if bootstatus is None:
+ return True
+ current_bootstatus = self.verify_bootstatus(entry, bootstatus)
+
+ if entry.get('status') == 'ignore':
+ # 'ignore' should verify
+ current_svcstatus = True
+ svcstatus = True
+ else:
+ svcstatus = self.check_service(entry)
+ if entry.get('status') == 'on':
+ if svcstatus:
+ current_svcstatus = True
+ else:
+ current_svcstatus = False
+ elif entry.get('status') == 'off':
+ if svcstatus:
+ current_svcstatus = False
+ else:
+ current_svcstatus = True
+
+ if svcstatus:
+ entry.set('current_status', 'on')
+ else:
+ entry.set('current_status', 'off')
+
+ return current_bootstatus and current_svcstatus
+
+ def InstallService(self, entry):
+ """Install Service entry."""
+ self.logger.info("Installing Service %s" % (entry.get('name')))
+ bootstatus = self.get_bootstatus(entry)
+
+ # check if service exists
+ all_services_cmd = '/usr/sbin/service -l'
+ all_services = self.cmd.run(all_services_cmd).stdout.splitlines()
+ if entry.get('name') not in all_services:
+ self.logger.debug("Service %s does not exist" % entry.get('name'))
+ return False
+
+ # get rcvar for service
+ vars = set()
+ rcvar_cmd = self.get_svc_command(entry, 'rcvar')
+ for line in self.cmd.run(rcvar_cmd).stdout.splitlines():
+ match = self.rcvar_re.match(line)
+ if match:
+ vars.add(match.group('var'))
+
+ if bootstatus is not None:
+ bootcmdrv = True
+ sysrcstatus = None
+ if bootstatus == 'on':
+ sysrcstatus = 'YES'
+ elif bootstatus == 'off':
+ sysrcstatus = 'NO'
+ if sysrcstatus is not None:
+ for var in vars:
+ if not self.cmd.run('/usr/sbin/sysrc %s="%s"' % (var, sysrcstatus)):
+ bootcmdrv = False
+ break
+
+ if Bcfg2.Options.setup.service_mode == 'disabled':
+ # 'disabled' means we don't attempt to modify running svcs
+ return bootcmdrv
+ buildmode = Bcfg2.Options.setup.service_mode == 'build'
+ if (entry.get('status') == 'on' and not buildmode) and \
+ entry.get('current_status') == 'off':
+ svccmdrv = self.start_service(entry)
+ elif (entry.get('status') == 'off' or buildmode) and \
+ entry.get('current_status') == 'on':
+ svccmdrv = self.stop_service(entry)
+ else:
+ svccmdrv = True # ignore status attribute
+ return bootcmdrv and svccmdrv
+ else:
+ # when bootstatus is 'None', status == 'ignore'
+ return True
+
+ def FindExtra(self):
+ """Find Extra FreeBSD Service entries."""
+ specified = [entry.get('name') for entry in self.getSupportedEntries()]
+ extra = set()
+ for path in self.cmd.run("/usr/sbin/service -e").stdout.splitlines():
+ name = os.path.basename(path)
+ if name not in specified:
+ extra.add(name)
+ return [Bcfg2.Client.XML.Element('Service', name=name, type='freebsd')
+ for name in list(extra)]
+
+ def Remove(self, _):
+ """Remove extra service entries."""
+ # Extra service removal is nonsensical
+ # Extra services need to be reflected in the config
+ return
diff --git a/src/lib/Bcfg2/Client/Tools/HomeBrew.py b/src/lib/Bcfg2/Client/Tools/HomeBrew.py
new file mode 100644
index 000000000..d2f251230
--- /dev/null
+++ b/src/lib/Bcfg2/Client/Tools/HomeBrew.py
@@ -0,0 +1,54 @@
+"""This provides Bcfg2 support for homebrew packages."""
+
+import Bcfg2.Client.Tools
+
+
+class HomeBrew(Bcfg2.Client.Tools.PkgTool):
+ """Homebrew package support."""
+ name = 'HomeBrew'
+ __execs__ = ["/usr/local/bin/brew"]
+ __handles__ = [('Package', 'homebrew')]
+ __req__ = {'Package': ['name', 'version']}
+ pkgtype = 'homebrew'
+ pkgtool = ('/usr/local/bin/brew install %s', ('%s', ['name']))
+
+ def RefreshPackages(self):
+ """Refresh memory hashes of packages."""
+ pkgcache = self.cmd.run(["/usr/local/bin/brew",
+ "list", "--versions"]).stdout.splitlines()
+ self.installed = {}
+ for pkg in pkgcache:
+ pkgname, version = pkg.strip().split()
+ self.logger.debug(" pkgname: %s version: %s" % (pkgname, version))
+ self.installed[pkgname] = version
+
+ def VerifyPackage(self, entry, _):
+ """Verify Package status for entry."""
+ self.logger.debug("VerifyPackage: %s : %s" % (entry.get('name'),
+ entry.get('version')))
+
+ if entry.attrib['name'] in self.installed:
+ if (self.installed[entry.attrib['name']] ==
+ entry.attrib['version'] or
+ entry.attrib['version'] == 'any'):
+ return True
+ else:
+ self.logger.info(" %s: Wrong version installed. "
+ "Want %s, but have %s" %
+ (entry.get("name"),
+ entry.get("version"),
+ self.installed[entry.get("name")],
+ ))
+
+ entry.set('current_version', self.installed[entry.get('name')])
+ return False
+ entry.set('current_exists', 'false')
+ return False
+
+ def Remove(self, packages):
+ """Remove extra packages."""
+ pkg_names = [p.get('name') for p in packages]
+ self.logger.info("Removing packages: %s" % pkg_names)
+ self.cmd.run(["/usr/local/bin/brew", "uninstall"] + pkg_names)
+ self.RefreshPackages()
+ self.extra = self.FindExtra()
diff --git a/src/lib/Bcfg2/Client/Tools/IPS.py b/src/lib/Bcfg2/Client/Tools/IPS.py
index 5be8527bf..0f82b1bc1 100644
--- a/src/lib/Bcfg2/Client/Tools/IPS.py
+++ b/src/lib/Bcfg2/Client/Tools/IPS.py
@@ -15,14 +15,13 @@ class IPS(Bcfg2.Client.Tools.PkgTool):
__req__ = {'Package': ['name', 'version']}
pkgtool = ('pkg install --no-refresh %s', ('%s', ['name']))
- def __init__(self, logger, setup, cfg):
+ def __init__(self, config):
self.installed = {}
self.pending_upgrades = set()
self.image = image.Image()
self.image.find_root('/', False)
self.image.load_config()
- Bcfg2.Client.Tools.PkgTool.__init__(self, logger, setup, cfg)
- self.cfg = cfg
+ Bcfg2.Client.Tools.PkgTool.__init__(self, config)
def RefreshPackages(self):
self.installed = dict()
diff --git a/src/lib/Bcfg2/Client/Tools/MacPorts.py b/src/lib/Bcfg2/Client/Tools/MacPorts.py
index 116b24687..3c824eaff 100644
--- a/src/lib/Bcfg2/Client/Tools/MacPorts.py
+++ b/src/lib/Bcfg2/Client/Tools/MacPorts.py
@@ -12,11 +12,6 @@ class MacPorts(Bcfg2.Client.Tools.PkgTool):
pkgtype = 'macport'
pkgtool = ('/opt/local/bin/port install %s', ('%s', ['name']))
- def __init__(self, logger, setup, config):
- Bcfg2.Client.Tools.PkgTool.__init__(self, logger, setup, config)
- self.installed = {}
- self.RefreshPackages()
-
def RefreshPackages(self):
"""Refresh memory hashes of packages."""
pkgcache = self.cmd.run(["/opt/local/bin/port",
diff --git a/src/lib/Bcfg2/Client/Tools/OpenCSW.py b/src/lib/Bcfg2/Client/Tools/OpenCSW.py
index 60e362e64..3ea9d835e 100644
--- a/src/lib/Bcfg2/Client/Tools/OpenCSW.py
+++ b/src/lib/Bcfg2/Client/Tools/OpenCSW.py
@@ -14,9 +14,9 @@ class OpenCSW(Bcfg2.Client.Tools.SYSV.SYSV):
__handles__ = [('Package', 'opencsw')]
__req__ = {'Package': ['name', 'version', 'bname']}
- def __init__(self, logger, setup, config):
+ def __init__(self, config):
# dont use the sysv constructor
- Bcfg2.Client.Tools.PkgTool.__init__(self, logger, setup, config)
+ Bcfg2.Client.Tools.PkgTool.__init__(self, config)
noaskfile = tempfile.NamedTemporaryFile()
self.noaskname = noaskfile.name
try:
diff --git a/src/lib/Bcfg2/Client/Tools/POSIX/Augeas.py b/src/lib/Bcfg2/Client/Tools/POSIX/Augeas.py
index 8506f4bc7..fc4e16904 100644
--- a/src/lib/Bcfg2/Client/Tools/POSIX/Augeas.py
+++ b/src/lib/Bcfg2/Client/Tools/POSIX/Augeas.py
@@ -190,12 +190,12 @@ class POSIXAugeas(POSIXTool):
:ref:`client-tools-augeas`. """
__req__ = ['name', 'mode', 'owner', 'group']
- def __init__(self, logger, setup, config):
- POSIXTool.__init__(self, logger, setup, config)
+ def __init__(self, config):
+ POSIXTool.__init__(self, config)
self._augeas = dict()
# file tool for setting initial values of files that don't
# exist
- self.filetool = POSIXFile(logger, setup, config)
+ self.filetool = POSIXFile(config)
def get_augeas(self, entry):
""" Get an augeas object for the given entry. """
diff --git a/src/lib/Bcfg2/Client/Tools/POSIX/Device.py b/src/lib/Bcfg2/Client/Tools/POSIX/Device.py
index 9b84adad0..6237ccce2 100644
--- a/src/lib/Bcfg2/Client/Tools/POSIX/Device.py
+++ b/src/lib/Bcfg2/Client/Tools/POSIX/Device.py
@@ -13,7 +13,7 @@ class POSIXDevice(POSIXTool):
if entry.get('dev_type') in ['block', 'char']:
# check if major/minor are properly specified
if (entry.get('major') is None or
- entry.get('minor') is None):
+ entry.get('minor') is None):
return False
return True
diff --git a/src/lib/Bcfg2/Client/Tools/POSIX/File.py b/src/lib/Bcfg2/Client/Tools/POSIX/File.py
index b1bde1057..fc445e07c 100644
--- a/src/lib/Bcfg2/Client/Tools/POSIX/File.py
+++ b/src/lib/Bcfg2/Client/Tools/POSIX/File.py
@@ -3,9 +3,9 @@
import os
import sys
import stat
-import time
import difflib
import tempfile
+import Bcfg2.Options
from Bcfg2.Client.Tools.POSIX.base import POSIXTool
from Bcfg2.Compat import unicode, b64encode, b64decode # pylint: disable=W0622
@@ -43,7 +43,7 @@ class POSIXFile(POSIXTool):
tempdata = entry.text
if isinstance(tempdata, unicode) and unicode != str:
try:
- tempdata = tempdata.encode(self.setup['encoding'])
+ tempdata = tempdata.encode(Bcfg2.Options.setup.encoding)
except UnicodeEncodeError:
err = sys.exc_info()[1]
self.logger.error("POSIX: Error encoding file %s: %s" %
@@ -56,7 +56,7 @@ class POSIXFile(POSIXTool):
if isinstance(tempdata, str) and str != unicode:
tempdatasize = len(tempdata)
else:
- tempdatasize = len(tempdata.encode(self.setup['encoding']))
+ tempdatasize = len(tempdata.encode(Bcfg2.Options.setup.encoding))
different = False
content = None
@@ -78,7 +78,7 @@ class POSIXFile(POSIXTool):
content = open(entry.get('name')).read()
except UnicodeDecodeError:
content = open(entry.get('name'),
- encoding=self.setup['encoding']).read()
+ encoding=Bcfg2.Options.setup.encoding).read()
except IOError:
self.logger.error("POSIX: Failed to read %s: %s" %
(entry.get("name"), sys.exc_info()[1]))
@@ -89,7 +89,7 @@ class POSIXFile(POSIXTool):
self.logger.debug("POSIX: %s has incorrect contents" %
entry.get("name"))
self._get_diffs(
- entry, interactive=self.setup['interactive'],
+ entry, interactive=Bcfg2.Options.setup.interactive,
sensitive=entry.get('sensitive', 'false').lower() == 'true',
is_binary=is_binary, content=content)
return POSIXTool.verify(self, entry, modlist) and not different
@@ -116,7 +116,7 @@ class POSIXFile(POSIXTool):
os.fdopen(newfd, 'w').write(filedata)
else:
os.fdopen(newfd, 'wb').write(
- filedata.encode(self.setup['encoding']))
+ filedata.encode(Bcfg2.Options.setup.encoding))
except (OSError, IOError):
err = sys.exc_info()[1]
self.logger.error("POSIX: Failed to open temp file %s for writing "
@@ -181,20 +181,20 @@ class POSIXFile(POSIXTool):
(entry.get("name"), sys.exc_info()[1]))
return False
if not is_binary:
- is_binary |= not self._is_string(content, self.setup['encoding'])
+ is_binary |= not self._is_string(content,
+ Bcfg2.Options.setup.encoding)
if is_binary:
# don't compute diffs if the file is binary
prompt.append('Binary file, no printable diff')
attrs['current_bfile'] = b64encode(content)
else:
+ diff = self._diff(content, self._get_data(entry)[0],
+ filename=entry.get("name"))
if interactive:
- diff = self._diff(content, self._get_data(entry)[0],
- difflib.unified_diff,
- filename=entry.get("name"))
if diff:
- udiff = '\n'.join(l.rstrip('\n') for l in diff)
+ udiff = '\n'.join(diff)
if hasattr(udiff, "decode"):
- udiff = udiff.decode(self.setup['encoding'])
+ udiff = udiff.decode(Bcfg2.Options.setup.encoding)
try:
prompt.append(udiff)
except UnicodeEncodeError:
@@ -207,8 +207,6 @@ class POSIXFile(POSIXTool):
prompt.append("Diff took too long to compute, no "
"printable diff")
if not sensitive:
- diff = self._diff(content, self._get_data(entry)[0],
- difflib.ndiff, filename=entry.get("name"))
if diff:
attrs["current_bdiff"] = b64encode("\n".join(diff))
else:
@@ -219,28 +217,16 @@ class POSIXFile(POSIXTool):
for attr, val in attrs.items():
entry.set(attr, val)
- def _diff(self, content1, content2, difffunc, filename=None):
- """ Return a diff of the two strings, as produced by difffunc.
- warns after 5 seconds and times out after 30 seconds. """
- rv = []
- start = time.time()
- longtime = False
- for diffline in difffunc(content1.split('\n'),
- content2.split('\n')):
- now = time.time()
- rv.append(diffline)
- if now - start > 5 and not longtime:
- if filename:
- self.logger.info("POSIX: Diff of %s taking a long time" %
- filename)
- else:
- self.logger.info("POSIX: Diff taking a long time")
- longtime = True
- elif now - start > 30:
- if filename:
- self.logger.error("POSIX: Diff of %s took too long; "
- "giving up" % filename)
- else:
- self.logger.error("POSIX: Diff took too long; giving up")
- return False
- return rv
+ def _diff(self, content1, content2, filename=None):
+ """ Return a unified diff of the two strings """
+
+ if filename:
+ fromfile = "%s (on disk)" % filename
+ tofile = "%s (from bcfg2)" % filename
+ else:
+ fromfile = ""
+ tofile = ""
+ return difflib.unified_diff(content1.split('\n'),
+ content2.split('\n'),
+ fromfile=fromfile,
+ tofile=tofile)
diff --git a/src/lib/Bcfg2/Client/Tools/POSIX/Nonexistent.py b/src/lib/Bcfg2/Client/Tools/POSIX/Nonexistent.py
index f7251ca50..d67a68c8b 100644
--- a/src/lib/Bcfg2/Client/Tools/POSIX/Nonexistent.py
+++ b/src/lib/Bcfg2/Client/Tools/POSIX/Nonexistent.py
@@ -24,8 +24,8 @@ class POSIXNonexistent(POSIXTool):
for struct in self.config.getchildren():
for el in struct.getchildren():
if (el.tag == 'Path' and
- el.get('type') != 'nonexistent' and
- el.get('name').startswith(ename)):
+ el.get('type') != 'nonexistent' and
+ el.get('name').startswith(ename)):
self.logger.error('POSIX: Not removing %s. One or '
'more files in this directory are '
'specified in your configuration.' %
diff --git a/src/lib/Bcfg2/Client/Tools/POSIX/__init__.py b/src/lib/Bcfg2/Client/Tools/POSIX/__init__.py
index 8d64cf84d..c27c7559d 100644
--- a/src/lib/Bcfg2/Client/Tools/POSIX/__init__.py
+++ b/src/lib/Bcfg2/Client/Tools/POSIX/__init__.py
@@ -4,20 +4,31 @@ import os
import re
import sys
import shutil
-from datetime import datetime
+import Bcfg2.Options
import Bcfg2.Client.Tools
+from datetime import datetime
from Bcfg2.Compat import walk_packages
from Bcfg2.Client.Tools.POSIX.base import POSIXTool
class POSIX(Bcfg2.Client.Tools.Tool):
"""POSIX File support code."""
- name = 'POSIX'
- def __init__(self, logger, setup, config):
- Bcfg2.Client.Tools.Tool.__init__(self, logger, setup, config)
- self.ppath = setup['ppath']
- self.max_copies = setup['max_copies']
+ options = Bcfg2.Client.Tools.Tool.options + [
+ Bcfg2.Options.PathOption(
+ cf=('paranoid', 'path'), default='/var/cache/bcfg2',
+ dest='paranoid_path',
+ help='Specify path for paranoid file backups'),
+ Bcfg2.Options.Option(
+ cf=('paranoid', 'max_copies'), default=1, type=int,
+ dest='paranoid_copies',
+ help='Specify the number of paranoid copies you want'),
+ Bcfg2.Options.BooleanOption(
+ '-P', '--paranoid', cf=('client', 'paranoid'),
+ help='Make automatic backups of config files')]
+
+ def __init__(self, config):
+ Bcfg2.Client.Tools.Tool.__init__(self, config)
self._handlers = self._load_handlers()
self.logger.debug("POSIX: Handlers loaded: %s" %
(", ".join(self._handlers.keys())))
@@ -56,7 +67,7 @@ class POSIX(Bcfg2.Client.Tools.Tool):
if POSIXTool in hdlr.__mro__:
# figure out what entry type this handler handles
etype = hdlr.__name__[5:].lower()
- rv[etype] = hdlr(self.logger, self.setup, self.config)
+ rv[etype] = hdlr(self.config)
return rv
def canVerify(self, entry):
@@ -92,7 +103,7 @@ class POSIX(Bcfg2.Client.Tools.Tool):
self.logger.debug("POSIX: Verifying entry %s:%s:%s" %
(entry.tag, entry.get("type"), entry.get("name")))
ret = self._handlers[entry.get("type")].verify(entry, modlist)
- if self.setup['interactive'] and not ret:
+ if Bcfg2.Options.setup.interactive and not ret:
entry.set('qtext',
'%s\nInstall %s %s: (y/N) ' %
(entry.get('qtext', ''),
@@ -106,35 +117,39 @@ class POSIX(Bcfg2.Client.Tools.Tool):
bkupnam + r'_\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{6}$')
# current list of backups for this file
try:
- bkuplist = [f for f in os.listdir(self.ppath) if
- bkup_re.match(f)]
+ bkuplist = [f
+ for f in os.listdir(Bcfg2.Options.setup.paranoid_path)
+ if bkup_re.match(f)]
except OSError:
err = sys.exc_info()[1]
self.logger.error("POSIX: Failed to create backup list in %s: %s" %
- (self.ppath, err))
+ (Bcfg2.Options.setup.paranoid_path, err))
return
bkuplist.sort()
- while len(bkuplist) >= int(self.max_copies):
+ while len(bkuplist) >= int(Bcfg2.Options.setup.paranoid_copies):
# remove the oldest backup available
oldest = bkuplist.pop(0)
self.logger.info("POSIX: Removing old backup %s" % oldest)
try:
- os.remove(os.path.join(self.ppath, oldest))
+ os.remove(os.path.join(Bcfg2.Options.setup.paranoid_path,
+ oldest))
except OSError:
err = sys.exc_info()[1]
- self.logger.error("POSIX: Failed to remove old backup %s: %s" %
- (os.path.join(self.ppath, oldest), err))
+ self.logger.error(
+ "POSIX: Failed to remove old backup %s: %s" %
+ (os.path.join(Bcfg2.Options.setup.paranoid_path, oldest),
+ err))
def _paranoid_backup(self, entry):
""" Take a backup of the specified entry for paranoid mode """
if (entry.get("paranoid", 'false').lower() == 'true' and
- self.setup.get("paranoid", False) and
- entry.get('current_exists', 'true') == 'true' and
- not os.path.isdir(entry.get("name"))):
+ Bcfg2.Options.setup.paranoid and
+ entry.get('current_exists', 'true') == 'true' and
+ not os.path.isdir(entry.get("name"))):
self._prune_old_backups(entry)
bkupnam = "%s_%s" % (entry.get('name').replace('/', '_'),
datetime.isoformat(datetime.now()))
- bfile = os.path.join(self.ppath, bkupnam)
+ bfile = os.path.join(Bcfg2.Options.setup.paranoid_path, bkupnam)
try:
shutil.copy(entry.get('name'), bfile)
self.logger.info("POSIX: Backup of %s saved to %s" %
diff --git a/src/lib/Bcfg2/Client/Tools/POSIX/base.py b/src/lib/Bcfg2/Client/Tools/POSIX/base.py
index 1786fa83a..488920989 100644
--- a/src/lib/Bcfg2/Client/Tools/POSIX/base.py
+++ b/src/lib/Bcfg2/Client/Tools/POSIX/base.py
@@ -10,6 +10,7 @@ import errno
import shutil
import Bcfg2.Client.Tools
import Bcfg2.Client.XML
+import Bcfg2.Options
from Bcfg2.Compat import oct_mode
try:
@@ -38,6 +39,22 @@ device_map = dict(block=stat.S_IFBLK, # pylint: disable=C0103
class POSIXTool(Bcfg2.Client.Tools.Tool):
""" Base class for tools that handle POSIX (Path) entries """
+
+ options = [
+ Bcfg2.Options.Option(
+ cf=('POSIX', 'secontext_ignore'),
+ default=['anon_inodefs_t', 'bdev_t', 'binfmt_misc_fs_t',
+ 'capifs_t', 'configfs_t', 'cpusetfs_t', 'ecryptfs_t',
+ 'eventpollfs_t', 'futexfs_t', 'hugetlbfs_t', 'ibmasmfs_t',
+ 'inotifyfs_t', 'mvfs_t', 'nfsd_fs_t', 'oprofilefs_t',
+ 'ramfs_t', 'romfs_t', 'rpc_pipefs_t', 'spufs_t',
+ 'squash_t', 'vmblock_t', 'vxfs_t', 'xenfs_t', 'autofs_t',
+ 'cifs_t', 'dosfs_t', 'fusefs_t', 'iso9660_t',
+ 'removable_t', 'nfs_t'],
+ help='secontext types to ignore labeling errors',
+ type=Bcfg2.Options.Types.colon_list)
+ ]
+
def fully_specified(self, entry): # pylint: disable=W0613
""" return True if the entry is fully specified """
# checking is done by __req__
@@ -106,23 +123,23 @@ class POSIXTool(Bcfg2.Client.Tools.Tool):
path = entry.get("name")
rv = True
- if entry.get("owner") and entry.get("group"):
- try:
- self.logger.debug("POSIX: Setting ownership of %s to %s:%s" %
- (path,
- self._norm_entry_uid(entry),
- self._norm_entry_gid(entry)))
- os.chown(path, self._norm_entry_uid(entry),
- self._norm_entry_gid(entry))
- except KeyError:
- self.logger.error('POSIX: Failed to change ownership of %s' %
- path)
- rv = False
- os.chown(path, 0, 0)
- except OSError:
- self.logger.error('POSIX: Failed to change ownership of %s' %
- path)
- rv = False
+ if os.geteuid() == 0:
+ if entry.get("owner") and entry.get("group"):
+ try:
+ self.logger.debug("POSIX: Setting ownership of %s to %s:%s"
+ % (path,
+ self._norm_entry_uid(entry),
+ self._norm_entry_gid(entry)))
+ os.chown(path, self._norm_entry_uid(entry),
+ self._norm_entry_gid(entry))
+ except (OSError, KeyError):
+ self.logger.error('POSIX: Failed to change ownership of %s'
+ % path)
+ rv = False
+ if sys.exc_info()[0] == KeyError:
+ os.chown(path, 0, 0)
+ else:
+ self.logger.debug("POSIX: Run as non-root, not setting ownership")
if entry.get("mode"):
wanted_mode = int(entry.get('mode'), 8)
@@ -286,7 +303,7 @@ class POSIXTool(Bcfg2.Client.Tools.Tool):
# no context listed
return True
secontext = selinux.lgetfilecon(path)[1].split(":")[2]
- if secontext in self.setup["posix_secontext_ignore"]:
+ if secontext in Bcfg2.Options.setup.posix_secontext_ignore:
return True
try:
if context == '__default__':
@@ -522,7 +539,8 @@ class POSIXTool(Bcfg2.Client.Tools.Tool):
(path, attrib['current_group'], entry.get('group')))
if (wanted_mode and
- oct_mode(int(attrib['current_mode'], 8)) != oct_mode(wanted_mode)):
+ oct_mode(int(attrib['current_mode'], 8)) !=
+ oct_mode(wanted_mode)):
errors.append("Permissions for path %s are incorrect. "
"Current permissions are %s but should be %s" %
(path, attrib['current_mode'], entry.get('mode')))
@@ -547,7 +565,7 @@ class POSIXTool(Bcfg2.Client.Tools.Tool):
else:
wanted_secontext = entry.get("secontext")
if (wanted_secontext and
- attrib['current_secontext'] != wanted_secontext):
+ attrib['current_secontext'] != wanted_secontext):
errors.append("SELinux context for path %s is incorrect. "
"Current context is %s but should be %s" %
(path, attrib['current_secontext'],
diff --git a/src/lib/Bcfg2/Client/Tools/POSIXUsers.py b/src/lib/Bcfg2/Client/Tools/POSIXUsers.py
index b8451d9d6..40598541e 100644
--- a/src/lib/Bcfg2/Client/Tools/POSIXUsers.py
+++ b/src/lib/Bcfg2/Client/Tools/POSIXUsers.py
@@ -3,14 +3,38 @@ and groupadd/mod/del """
import pwd
import grp
+import Bcfg2.Options
import Bcfg2.Client.XML
import Bcfg2.Client.Tools
from Bcfg2.Utils import PackedDigitRange
+def uid_range_type(val):
+ """ Option type to unpack a list of numerical ranges """
+ return PackedDigitRange(*Bcfg2.Options.Types.comma_list(val))
+
+
class POSIXUsers(Bcfg2.Client.Tools.Tool):
""" A tool to handle creating users and groups with
useradd/mod/del and groupadd/mod/del """
+ options = Bcfg2.Client.Tools.Tool.options + [
+ Bcfg2.Options.Option(
+ cf=('POSIXUsers', 'uid_whitelist'), default=[],
+ type=uid_range_type,
+ help="UID ranges the POSIXUsers tool will manage"),
+ Bcfg2.Options.Option(
+ cf=('POSIXUsers', 'gid_whitelist'), default=[],
+ type=uid_range_type,
+ help="GID ranges the POSIXUsers tool will manage"),
+ Bcfg2.Options.Option(
+ cf=('POSIXUsers', 'uid_blacklist'), default=[],
+ type=uid_range_type,
+ help="UID ranges the POSIXUsers tool will not manage"),
+ Bcfg2.Options.Option(
+ cf=('POSIXUsers', 'gid_blacklist'), default=[],
+ type=uid_range_type,
+ help="GID ranges the POSIXUsers tool will not manage")]
+
__execs__ = ['/usr/sbin/useradd', '/usr/sbin/usermod', '/usr/sbin/userdel',
'/usr/sbin/groupadd', '/usr/sbin/groupmod',
'/usr/sbin/groupdel']
@@ -18,7 +42,6 @@ class POSIXUsers(Bcfg2.Client.Tools.Tool):
('POSIXGroup', None)]
__req__ = dict(POSIXUser=['name'],
POSIXGroup=['name'])
- experimental = True
#: A mapping of XML entry attributes to the indexes of
#: corresponding values in the get{pw|gr}all data structures
@@ -30,25 +53,15 @@ class POSIXUsers(Bcfg2.Client.Tools.Tool):
#: user or group
id_mapping = dict(POSIXUser="uid", POSIXGroup="gid")
- def __init__(self, logger, setup, config):
- Bcfg2.Client.Tools.Tool.__init__(self, logger, setup, config)
+ def __init__(self, config):
+ Bcfg2.Client.Tools.Tool.__init__(self, config)
self.set_defaults = dict(POSIXUser=self.populate_user_entry,
POSIXGroup=lambda g: g)
self._existing = None
- self._whitelist = dict(POSIXUser=None, POSIXGroup=None)
- self._blacklist = dict(POSIXUser=None, POSIXGroup=None)
- if self.setup['posix_uid_whitelist']:
- self._whitelist['POSIXUser'] = \
- PackedDigitRange(*self.setup['posix_uid_whitelist'])
- else:
- self._blacklist['POSIXUser'] = \
- PackedDigitRange(*self.setup['posix_uid_blacklist'])
- if self.setup['posix_gid_whitelist']:
- self._whitelist['POSIXGroup'] = \
- PackedDigitRange(*self.setup['posix_gid_whitelist'])
- else:
- self._blacklist['POSIXGroup'] = \
- PackedDigitRange(*self.setup['posix_gid_blacklist'])
+ self._whitelist = dict(POSIXUser=Bcfg2.Options.setup.uid_whitelist,
+ POSIXGroup=Bcfg2.Options.setup.gid_whitelist)
+ self._blacklist = dict(POSIXUser=Bcfg2.Options.setup.uid_blacklist,
+ POSIXGroup=Bcfg2.Options.setup.gid_blacklist)
@property
def existing(self):
@@ -66,7 +79,7 @@ class POSIXUsers(Bcfg2.Client.Tools.Tool):
defined, and the uid/gid is in that whitelist; or b) no
whitelist is defined, and the uid/gid is not in the
blacklist. """
- if self._whitelist[tag] is None:
+ if not self._whitelist[tag]:
return eid not in self._blacklist[tag]
else:
return eid in self._whitelist[tag]
@@ -87,7 +100,7 @@ class POSIXUsers(Bcfg2.Client.Tools.Tool):
return False
return True
- def Inventory(self, states, structures=None):
+ def Inventory(self, structures=None):
if not structures:
structures = self.config.getchildren()
# we calculate a list of all POSIXUser and POSIXGroup entries,
@@ -107,7 +120,8 @@ class POSIXUsers(Bcfg2.Client.Tools.Tool):
(group, entry.get("name")))
struct.append(Bcfg2.Client.XML.Element("POSIXGroup",
name=group))
- return Bcfg2.Client.Tools.Tool.Inventory(self, states, structures)
+ return Bcfg2.Client.Tools.Tool.Inventory(self, structures)
+ Inventory.__doc__ = Bcfg2.Client.Tools.Tool.Inventory.__doc__
def FindExtra(self):
extra = []
@@ -165,7 +179,7 @@ class POSIXUsers(Bcfg2.Client.Tools.Tool):
% (entry.tag, entry.get("name"),
actual, expected)]))
rv = False
- if self.setup['interactive'] and not rv:
+ if Bcfg2.Options.setup.interactive and not rv:
entry.set('qtext',
'%s\nInstall %s %s: (y/N) ' %
(entry.get('qtext', ''), entry.tag, entry.get('name')))
@@ -174,7 +188,7 @@ class POSIXUsers(Bcfg2.Client.Tools.Tool):
def VerifyPOSIXGroup(self, entry, _):
""" Verify a POSIXGroup entry """
rv = self._verify(entry)
- if self.setup['interactive'] and not rv:
+ if Bcfg2.Options.setup.interactive and not rv:
entry.set('qtext',
'%s\nInstall %s %s: (y/N) ' %
(entry.get('qtext', ''), entry.tag, entry.get('name')))
@@ -191,7 +205,7 @@ class POSIXUsers(Bcfg2.Client.Tools.Tool):
for attr, idx in self.attr_mapping[entry.tag].items():
val = str(self.existing[entry.tag][entry.get("name")][idx])
entry.set("current_%s" %
- attr, val.decode(self.setup['encoding']))
+ attr, val.decode(Bcfg2.Options.setup.encoding))
if attr in ["uid", "gid"]:
if entry.get(attr) is None:
# no uid/gid specified, so we let the tool
@@ -213,7 +227,8 @@ class POSIXUsers(Bcfg2.Client.Tools.Tool):
entry.set('qtext', "\n".join([entry.get('qtext', '')] + errors))
return len(errors) == 0
- def Install(self, entries, states):
+ def Install(self, entries):
+ states = dict()
for entry in entries:
# install groups first, so that all groups exist for
# users that might need them
@@ -223,6 +238,7 @@ class POSIXUsers(Bcfg2.Client.Tools.Tool):
if entry.tag == 'POSIXUser':
states[entry] = self._install(entry)
self._existing = None
+ return states
def _install(self, entry):
""" add or modify a user or group using the appropriate command """
diff --git a/src/lib/Bcfg2/Client/Tools/Pacman.py b/src/lib/Bcfg2/Client/Tools/Pacman.py
index b931fe028..b82b905e7 100644
--- a/src/lib/Bcfg2/Client/Tools/Pacman.py
+++ b/src/lib/Bcfg2/Client/Tools/Pacman.py
@@ -13,11 +13,6 @@ class Pacman(Bcfg2.Client.Tools.PkgTool):
pkgtype = 'pacman'
pkgtool = ("/usr/bin/pacman --needed --noconfirm --noprogressbar")
- def __init__(self, logger, setup, config):
- Bcfg2.Client.Tools.PkgTool.__init__(self, logger, setup, config)
- self.installed = {}
- self.RefreshPackages()
-
def RefreshPackages(self):
'''Refresh memory hashes of packages'''
self.installed = {}
@@ -42,8 +37,6 @@ class Pacman(Bcfg2.Client.Tools.PkgTool):
return True
elif self.installed[entry.attrib['name']] == \
entry.attrib['version']:
- # if (not self.setup['quick'] and
- # entry.get('verify', 'true') == 'true'):
# FIXME: need to figure out if pacman
# allows you to verify packages
return True
@@ -65,7 +58,7 @@ class Pacman(Bcfg2.Client.Tools.PkgTool):
self.RefreshPackages()
self.extra = self.FindExtra()
- def Install(self, packages, states):
+ def Install(self, packages):
'''
Pacman Install
'''
diff --git a/src/lib/Bcfg2/Client/Tools/Pkgng.py b/src/lib/Bcfg2/Client/Tools/Pkgng.py
new file mode 100644
index 000000000..eef86a131
--- /dev/null
+++ b/src/lib/Bcfg2/Client/Tools/Pkgng.py
@@ -0,0 +1,227 @@
+"""This is the Bcfg2 support for pkg."""
+
+import os
+import Bcfg2.Options
+import Bcfg2.Client.Tools
+
+
+class Pkgng(Bcfg2.Client.Tools.Tool):
+ """Support for pkgng packages on FreeBSD."""
+
+ options = Bcfg2.Client.Tools.Tool.options + [
+ Bcfg2.Options.PathOption(
+ cf=('Pkgng', 'path'),
+ default='/usr/sbin/pkg', dest='pkg_path',
+ help='Pkgng tool path')]
+
+ name = 'Pkgng'
+ __execs__ = []
+ __handles__ = [('Package', 'pkgng'), ('Path', 'ignore')]
+ __req__ = {'Package': ['name', 'version'], 'Path': ['type']}
+
+ def __init__(self, config):
+ Bcfg2.Client.Tools.Tool.__init__(self, config)
+
+ self.pkg = Bcfg2.Options.setup.pkg_path
+ self.__execs__ = [self.pkg]
+
+ self.pkgcmd = self.pkg + ' install -fy'
+ if not Bcfg2.Options.setup.debug:
+ self.pkgcmd += ' -q'
+ self.pkgcmd += ' %s'
+
+ self.ignores = [entry.get('name') for struct in config
+ for entry in struct
+ if entry.tag == 'Path' and
+ entry.get('type') == 'ignore']
+
+ self.__important__ = self.__important__ + \
+ [entry.get('name') for struct in config
+ for entry in struct
+ if (entry.tag == 'Path' and
+ entry.get('name').startswith('/etc/pkg/'))]
+ self.nonexistent = [entry.get('name') for struct in config
+ for entry in struct
+ if entry.tag == 'Path' and
+ entry.get('type') == 'nonexistent']
+ self.actions = {}
+ self.pkg_cache = {}
+
+ try:
+ self._load_pkg_cache()
+ except OSError:
+ raise Bcfg2.Client.Tools.ToolInstantiationError
+
+ def _load_pkg_cache(self):
+ """Cache the version of all currently installed packages."""
+ self.pkg_cache = {}
+ output = self.cmd.run([self.pkg, 'query', '-a', '%n %v']).stdout
+ for line in output.splitlines():
+ parts = line.split(' ')
+ name = ' '.join(parts[:-1])
+ self.pkg_cache[name] = parts[-1]
+
+ def FindExtra(self):
+ """Find extra packages."""
+ packages = [entry.get('name') for entry in self.getSupportedEntries()]
+ extras = [(name, value) for (name, value) in self.pkg_cache.items()
+ if name not in packages]
+ return [Bcfg2.Client.XML.Element('Package', name=name, type='pkgng',
+ current_version=version)
+ for (name, version) in extras]
+
+ def VerifyChecksums(self, entry, modlist):
+ """Verify the checksum of the files, owned by a package."""
+ output = self.cmd.run([self.pkg, 'check', '-s',
+ entry.get('name')]).stdout.splitlines()
+ files = []
+ for item in output:
+ if "checksum mismatch" in item:
+ files.append(item.split()[-1])
+ elif "No such file or directory" in item:
+ continue
+ else:
+ self.logger.error("Got Unsupported pattern %s "
+ "from pkg check" % item)
+
+ files = list(set(files) - set(self.ignores))
+ # We check if there is file in the checksum to do
+ if files:
+ # if files are found there we try to be sure our modlist is sane
+ # with erroneous symlinks
+ modlist = [os.path.realpath(filename) for filename in modlist]
+ bad = [filename for filename in files if filename not in modlist]
+ if bad:
+ self.logger.debug("It is suggested that you either manage "
+ "these files, revert the changes, or ignore "
+ "false failures:")
+ self.logger.info("Package %s failed validation. Bad files "
+ "are:" % entry.get('name'))
+ self.logger.info(bad)
+ entry.set('qtext',
+ "Reinstall Package %s-%s to fix failing files? "
+ "(y/N) " % (entry.get('name'), entry.get('version')))
+ return False
+ return True
+
+ def _get_candidate_versions(self, name):
+ """
+ Get versions of the specified package name available for
+ installation from the configured remote repositories.
+ """
+ output = self.cmd.run([self.pkg, 'search', '-U', '-Qversion', '-q',
+ '-Sname', '-e', name]).stdout.splitlines()
+ versions = []
+ for line in output:
+ versions.append(line)
+
+ if len(versions) == 0:
+ return None
+
+ return sorted(versions)
+
+ def VerifyPackage(self, entry, modlist, checksums=True):
+ """Verify package for entry."""
+ if 'version' not in entry.attrib:
+ self.logger.info("Cannot verify unversioned package %s" %
+ (entry.attrib['name']))
+ return False
+
+ pkgname = entry.get('name')
+ if pkgname not in self.pkg_cache:
+ self.logger.info("Package %s not installed" % (entry.get('name')))
+ entry.set('current_exists', 'false')
+ return False
+
+ installed_version = self.pkg_cache[pkgname]
+ candidate_versions = self._get_candidate_versions(pkgname)
+ if candidate_versions is not None:
+ candidate_version = candidate_versions[0]
+ else:
+ self.logger.error("Package %s is installed but no candidate"
+ "version was found." % (entry.get('name')))
+ return False
+
+ if entry.get('version').startswith('auto'):
+ desired_version = candidate_version
+ entry.set('version', "auto: %s" % desired_version)
+ elif entry.get('version').startswith('any'):
+ desired_version = installed_version
+ entry.set('version', "any: %s" % desired_version)
+ else:
+ desired_version = entry.get('version')
+
+ if desired_version != installed_version:
+ entry.set('current_version', installed_version)
+ entry.set('qtext', "Modify Package %s (%s -> %s)? (y/N) " %
+ (entry.get('name'), entry.get('current_version'),
+ desired_version))
+ return False
+ else:
+ # version matches
+ if (not Bcfg2.Options.setup.quick and
+ entry.get('verify', 'true') == 'true' and
+ checksums):
+ pkgsums = self.VerifyChecksums(entry, modlist)
+ return pkgsums
+ return True
+
+ def Remove(self, packages):
+ """Deal with extra configuration detected."""
+ pkgnames = " ".join([pkg.get('name') for pkg in packages])
+ if len(packages) > 0:
+ self.logger.info('Removing packages:')
+ self.logger.info(pkgnames)
+ self.cmd.run([self.pkg, 'delete', '-y', pkgnames])
+ self._load_pkg_cache()
+ self.modified += packages
+ self.extra = self.FindExtra()
+
+ def Install(self, packages):
+ ipkgs = []
+ bad_pkgs = []
+ for pkg in packages:
+ versions = self._get_candidate_versions(pkg.get('name'))
+ if versions is None:
+ self.logger.error("pkg has no information about package %s" %
+ (pkg.get('name')))
+ continue
+
+ if pkg.get('version').startswith('auto') or \
+ pkg.get('version').startswith('any'):
+ ipkgs.append("%s-%s" % (pkg.get('name'), versions[0]))
+ continue
+
+ if pkg.get('version') in versions:
+ ipkgs.append("%s-%s" % (pkg.get('name'), pkg.get('version')))
+ continue
+ else:
+ self.logger.error("Package %s: desired version %s not in %s" %
+ (pkg.get('name'), pkg.get('version'),
+ versions))
+ bad_pkgs.append(pkg.get('name'))
+
+ if bad_pkgs:
+ self.logger.error("Cannot find correct versions of packages:")
+ self.logger.error(bad_pkgs)
+ if not ipkgs:
+ return
+ if not self.cmd.run(self.pkgcmd % (" ".join(ipkgs))):
+ self.logger.error("pkg command failed")
+ self._load_pkg_cache()
+ self.extra = self.FindExtra()
+ mark = []
+ states = dict()
+ for package in packages:
+ states[package] = self.VerifyPackage(package, [], checksums=False)
+ if states[package]:
+ self.modified.append(package)
+ if package.get('origin') == 'Packages':
+ mark.append(package.get('name'))
+ if mark:
+ self.cmd.run([self.pkg, 'set', '-A1', '-y'] + mark)
+ return states
+
+ def VerifyPath(self, _entry, _):
+ """Do nothing here since we only verify Path type=ignore."""
+ return True
diff --git a/src/lib/Bcfg2/Client/Tools/Portage.py b/src/lib/Bcfg2/Client/Tools/Portage.py
index 78ccb2d37..5c092f46b 100644
--- a/src/lib/Bcfg2/Client/Tools/Portage.py
+++ b/src/lib/Bcfg2/Client/Tools/Portage.py
@@ -5,9 +5,13 @@ import Bcfg2.Client.Tools
class Portage(Bcfg2.Client.Tools.PkgTool):
- """The Gentoo toolset implements package and service operations and
- inherits the rest from Toolset.Toolset."""
- name = 'Portage'
+ """The Gentoo toolset implements package and service operations
+ and inherits the rest from Tools.Tool."""
+
+ options = Bcfg2.Client.Tools.PkgTool.options + [
+ Bcfg2.Options.BooleanOption(
+ cf=('Portage', 'binpkgonly'), help='Portage binary packages only')]
+
__execs__ = ['/usr/bin/emerge', '/usr/bin/equery']
__handles__ = [('Package', 'ebuild')]
__req__ = {'Package': ['name', 'version']}
@@ -17,17 +21,15 @@ class Portage(Bcfg2.Client.Tools.PkgTool):
'version']))
pkgtool = ('emerge %s', ('=%s-%s', ['name', 'version']))
- def __init__(self, logger, cfg, setup):
+ def __init__(self, config):
self._initialised = False
- Bcfg2.Client.Tools.PkgTool.__init__(self, logger, cfg, setup)
+ Bcfg2.Client.Tools.PkgTool.__init__(self, config)
self._initialised = True
self.__important__ = self.__important__ + ['/etc/make.conf']
self._pkg_pattern = re.compile(r'(.*)-(\d.*)')
self._ebuild_pattern = re.compile('(ebuild|binary)')
- self.cfg = cfg
self.installed = {}
- self._binpkgonly = self.setup.get('portage_binpkgonly', False)
- if self._binpkgonly:
+ if Bcfg2.Options.setup.binpkgonly:
self.pkgtool = self._binpkgtool
self.RefreshPackages()
@@ -62,9 +64,9 @@ class Portage(Bcfg2.Client.Tools.PkgTool):
version = self.installed[entry.get('name')]
entry.set('current_version', version)
- if not self.setup['quick']:
+ if not Bcfg2.Options.setup.quick:
if ('verify' not in entry.attrib or
- entry.get('verify').lower() == 'true'):
+ entry.get('verify').lower() == 'true'):
# Check the package if:
# - Not running in quick mode
diff --git a/src/lib/Bcfg2/Client/Tools/RPM.py b/src/lib/Bcfg2/Client/Tools/RPM.py
index a4dd2b730..464b7e389 100644
--- a/src/lib/Bcfg2/Client/Tools/RPM.py
+++ b/src/lib/Bcfg2/Client/Tools/RPM.py
@@ -1,12 +1,1140 @@
"""Bcfg2 Support for RPMS"""
-import os.path
+import os
import rpm
-import rpmtools
import Bcfg2.Client.Tools
+import grp
+import optparse
+import pwd
+import stat
+import sys
+try:
+ import hashlib
+ py24compat = False
+except ImportError:
+ # FIXME: Remove when client python dep is 2.5 or greater
+ py24compat = True
+ import md5
+
+# Determine what prelink tools we have available.
+# The isprelink module is a python extension that examines the ELF headers
+# to see if the file has been prelinked. If it is not present a lot of files
+# are unnecessarily run through the prelink command.
+try:
+ from isprelink import *
+ isprelink_imported = True
+except ImportError:
+ isprelink_imported = False
+
+# If the prelink command is installed on the system then we need to do
+# prelink -y on files.
+if os.access('/usr/sbin/prelink', os.X_OK):
+ prelink_exists = True
+else:
+ prelink_exists = False
+
+# If we don't have isprelink then we will use the prelink configuration file to
+# filter what we have to put through prelink -y.
+import re
+blacklist = []
+whitelist = []
+try:
+ f = open('/etc/prelink.conf', mode='r')
+ for line in f:
+ if line.startswith('#'):
+ continue
+ option, pattern = line.split()
+ if pattern.startswith('*.'):
+ pattern = pattern.replace('*.', '\.')
+ pattern += '$'
+ elif pattern.startswith('/'):
+ pattern = '^' + pattern
+ if option == '-b':
+ blacklist.append(pattern)
+ elif option == '-l':
+ whitelist.append(pattern)
+ f.close()
+except IOError:
+ pass
+
+blacklist_re = re.compile('|'.join(blacklist))
+whitelist_re = re.compile('|'.join(whitelist))
+
+# Flags that are not defined in rpm-python.
+# They are defined in lib/rpmcli.h
+# Bit(s) for verifyFile() attributes.
+#
+RPMVERIFY_NONE = 0
+RPMVERIFY_MD5 = 1 # 1 << 0 # from %verify(md5)
+RPMVERIFY_FILESIZE = 2 # 1 << 1 # from %verify(size)
+RPMVERIFY_LINKTO = 4 # 1 << 2 # from %verify(link)
+RPMVERIFY_USER = 8 # 1 << 3 # from %verify(user)
+RPMVERIFY_GROUP = 16 # 1 << 4 # from %verify(group)
+RPMVERIFY_MTIME = 32 # 1 << 5 # from %verify(mtime)
+RPMVERIFY_MODE = 64 # 1 << 6 # from %verify(mode)
+RPMVERIFY_RDEV = 128 # 1 << 7 # from %verify(rdev)
+RPMVERIFY_CONTEXTS = 32768 # (1 << 15) # from --nocontexts
+RPMVERIFY_READLINKFAIL = 268435456 # (1 << 28) # readlink failed
+RPMVERIFY_READFAIL = 536870912 # (1 << 29) # file read failed
+RPMVERIFY_LSTATFAIL = 1073741824 # (1 << 30) # lstat failed
+RPMVERIFY_LGETFILECONFAIL = 2147483648 # (1 << 31) # lgetfilecon failed
+
+RPMVERIFY_FAILURES = \
+ (RPMVERIFY_LSTATFAIL | RPMVERIFY_READFAIL |
+ RPMVERIFY_READLINKFAIL | RPMVERIFY_LGETFILECONFAIL)
+
+# Bit(s) to control rpm_verify() operation.
+#
+VERIFY_DEFAULT = 0, # /*!< */
+VERIFY_MD5 = 1 << 0 # /*!< from --nomd5 */
+VERIFY_SIZE = 1 << 1 # /*!< from --nosize */
+VERIFY_LINKTO = 1 << 2 # /*!< from --nolinkto */
+VERIFY_USER = 1 << 3 # /*!< from --nouser */
+VERIFY_GROUP = 1 << 4 # /*!< from --nogroup */
+VERIFY_MTIME = 1 << 5 # /*!< from --nomtime */
+VERIFY_MODE = 1 << 6 # /*!< from --nomode */
+VERIFY_RDEV = 1 << 7 # /*!< from --nodev */
+# /* bits 8-14 unused, reserved for rpmVerifyAttrs */
+VERIFY_CONTEXTS = 1 << 15 # /*!< verify: from --nocontexts */
+VERIFY_FILES = 1 << 16 # /*!< verify: from --nofiles */
+VERIFY_DEPS = 1 << 17 # /*!< verify: from --nodeps */
+VERIFY_SCRIPT = 1 << 18 # /*!< verify: from --noscripts */
+VERIFY_DIGEST = 1 << 19 # /*!< verify: from --nodigest */
+VERIFY_SIGNATURE = 1 << 20 # /*!< verify: from --nosignature */
+VERIFY_PATCHES = 1 << 21 # /*!< verify: from --nopatches */
+VERIFY_HDRCHK = 1 << 22 # /*!< verify: from --nohdrchk */
+VERIFY_FOR_LIST = 1 << 23 # /*!< query: from --list */
+VERIFY_FOR_STATE = 1 << 24 # /*!< query: from --state */
+VERIFY_FOR_DOCS = 1 << 25 # /*!< query: from --docfiles */
+VERIFY_FOR_CONFIG = 1 << 26 # /*!< query: from --configfiles */
+VERIFY_FOR_DUMPFILES = 1 << 27 # /*!< query: from --dump */
+# /* bits 28-31 used in rpmVerifyAttrs */
+
+# Comes from C cource. lib/rpmcli.h
+VERIFY_ATTRS = \
+ (VERIFY_MD5 | VERIFY_SIZE | VERIFY_LINKTO | VERIFY_USER | VERIFY_GROUP |
+ VERIFY_MTIME | VERIFY_MODE | VERIFY_RDEV | VERIFY_CONTEXTS)
+
+VERIFY_ALL = \
+ (VERIFY_ATTRS | VERIFY_FILES | VERIFY_DEPS | VERIFY_SCRIPT |
+ VERIFY_DIGEST | VERIFY_SIGNATURE | VERIFY_HDRCHK)
+
+
+# Some masks for what checks to NOT do on these file types.
+# The C code actiually resets these up for every file.
+DIR_FLAGS = ~(RPMVERIFY_MD5 | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME |
+ RPMVERIFY_LINKTO)
+
+# These file types all have the same mask, but hopefully this will make the
+# code more readable.
+FIFO_FLAGS = CHR_FLAGS = BLK_FLAGS = GHOST_FLAGS = DIR_FLAGS
+
+LINK_FLAGS = ~(RPMVERIFY_MD5 | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME |
+ RPMVERIFY_MODE | RPMVERIFY_USER | RPMVERIFY_GROUP)
+
+REG_FLAGS = ~(RPMVERIFY_LINKTO)
+
+
+def s_isdev(mode):
+ """
+ Check to see if a file is a device.
+
+ """
+ return stat.S_ISBLK(mode) | stat.S_ISCHR(mode)
+
+
+def rpmpackagelist(rts):
+ """
+ Equivalent of rpm -qa. Intended for RefreshPackages() in the RPM Driver.
+ Requires rpmtransactionset() to be run first to get a ts.
+ Returns a list of pkgspec dicts.
+
+ e.g. [{'name':'foo', 'epoch':'20', 'version':'1.2',
+ 'release':'5', 'arch':'x86_64' },
+ {'name':'bar', 'epoch':'10', 'version':'5.2',
+ 'release':'2', 'arch':'x86_64' }]
+
+ """
+ return [
+ {'name': header[rpm.RPMTAG_NAME],
+ 'epoch': header[rpm.RPMTAG_EPOCH],
+ 'version': header[rpm.RPMTAG_VERSION],
+ 'release': header[rpm.RPMTAG_RELEASE],
+ 'arch': header[rpm.RPMTAG_ARCH],
+ 'gpgkeyid':
+ header.sprintf("%|SIGGPG?{%{SIGGPG:pgpsig}}:{None}|").split()[-1]}
+ for header in rts.dbMatch()]
+
+
+def getindexbykeyword(index_ts, **kwargs):
+ """
+ Return list of indexs from the rpmdb matching keywords
+ ex: getHeadersByKeyword(name='foo', version='1', release='1')
+
+ Can be passed any structure that can be indexed by the pkgspec
+ keyswords as other keys are filtered out.
+
+ """
+ lst = []
+ name = kwargs.get('name')
+ if name:
+ index_mi = index_ts.dbMatch(rpm.RPMTAG_NAME, name)
+ else:
+ index_mi = index_ts.dbMatch()
+
+ if 'epoch' in kwargs:
+ if kwargs['epoch'] is not None and kwargs['epoch'] != 'None':
+ kwargs['epoch'] = int(kwargs['epoch'])
+ else:
+ del(kwargs['epoch'])
+
+ keywords = [key for key in list(kwargs.keys())
+ if key in ('name', 'epoch', 'version', 'release', 'arch')]
+ keywords_len = len(keywords)
+ for hdr in index_mi:
+ match = 0
+ for keyword in keywords:
+ if hdr[keyword] == kwargs[keyword]:
+ match += 1
+ if match == keywords_len:
+ lst.append(index_mi.instance())
+ del index_mi
+ return lst
+
+
+def getheadersbykeyword(header_ts, **kwargs):
+ """
+ Borrowed parts of this from from Yum. Need to fix it though.
+ Epoch is not handled right.
+
+ Return list of headers from the rpmdb matching keywords
+ ex: getHeadersByKeyword(name='foo', version='1', release='1')
+
+ Can be passed any structure that can be indexed by the pkgspec
+ keyswords as other keys are filtered out.
+
+ """
+ lst = []
+ name = kwargs.get('name')
+ if name:
+ header_mi = header_ts.dbMatch(rpm.RPMTAG_NAME, name)
+ else:
+ header_mi = header_ts.dbMatch()
+
+ if 'epoch' in kwargs:
+ if kwargs['epoch'] is not None and kwargs['epoch'] != 'None':
+ kwargs['epoch'] = int(kwargs['epoch'])
+ else:
+ del(kwargs['epoch'])
+
+ keywords = [key for key in list(kwargs.keys())
+ if key in ('name', 'epoch', 'version', 'release', 'arch')]
+ keywords_len = len(keywords)
+ for hdr in header_mi:
+ match = 0
+ for keyword in keywords:
+ if hdr[keyword] == kwargs[keyword]:
+ match += 1
+ if match == keywords_len:
+ lst.append(hdr)
+ del header_mi
+ return lst
+
+
+def prelink_md5_check(filename):
+ """
+ Checks if a file is prelinked. If it is run it through prelink -y
+ to get the unprelinked md5 and file size.
+
+ Return 0 if the file was not prelinked, otherwise return the file size.
+ Always return the md5.
+
+ """
+ prelink = False
+ try:
+ plf = open(filename, "rb")
+ except IOError:
+ return False, 0
+
+ if prelink_exists:
+ if isprelink_imported:
+ plfd = plf.fileno()
+ if isprelink(plfd):
+ plf.close()
+ cmd = '/usr/sbin/prelink -y %s 2> /dev/null' \
+ % (re.escape(filename))
+ plf = os.popen(cmd, 'rb')
+ prelink = True
+ elif (whitelist_re.search(filename) and not
+ blacklist_re.search(filename)):
+ plf.close()
+ cmd = '/usr/sbin/prelink -y %s 2> /dev/null' \
+ % (re.escape(filename))
+ plf = os.popen(cmd, 'rb')
+ prelink = True
+
+ fsize = 0
+ if py24compat:
+ chksum = md5.new()
+ else:
+ chksum = hashlib.md5()
+ while 1:
+ data = plf.read()
+ if not data:
+ break
+ fsize += len(data)
+ chksum.update(data)
+ plf.close()
+ file_md5 = chksum.hexdigest()
+ if prelink:
+ return file_md5, fsize
+ else:
+ return file_md5, 0
+
+
+def prelink_size_check(filename):
+ """
+ This check is only done if the prelink_md5_check() is not done first.
+
+ Checks if a file is prelinked. If it is run it through prelink -y
+ to get the unprelinked file size.
+
+ Return 0 if the file was not prelinked, otherwise return the file size.
+
+ """
+ fsize = 0
+ try:
+ plf = open(filename, "rb")
+ except IOError:
+ return False
+
+ if prelink_exists:
+ if isprelink_imported:
+ plfd = plf.fileno()
+ if isprelink(plfd):
+ plf.close()
+ cmd = '/usr/sbin/prelink -y %s 2> /dev/null' \
+ % (re.escape(filename))
+ plf = os.popen(cmd, 'rb')
+
+ while 1:
+ data = plf.read()
+ if not data:
+ break
+ fsize += len(data)
+
+ elif (whitelist_re.search(filename) and not
+ blacklist_re.search(filename)):
+ plf.close()
+ cmd = '/usr/sbin/prelink -y %s 2> /dev/null' \
+ % (re.escape(filename))
+ plf = os.popen(cmd, 'rb')
+
+ while 1:
+ data = plf.read()
+ if not data:
+ break
+ fsize += len(data)
+
+ plf.close()
+
+ return fsize
+
+
+def debug_verify_flags(vflags):
+ """
+ Decodes the verify flags bits.
+ """
+ if vflags & RPMVERIFY_MD5:
+ print('RPMVERIFY_MD5')
+ if vflags & RPMVERIFY_FILESIZE:
+ print('RPMVERIFY_FILESIZE')
+ if vflags & RPMVERIFY_LINKTO:
+ print('RPMVERIFY_LINKTO')
+ if vflags & RPMVERIFY_USER:
+ print('RPMVERIFY_USER')
+ if vflags & RPMVERIFY_GROUP:
+ print('RPMVERIFY_GROUP')
+ if vflags & RPMVERIFY_MTIME:
+ print('RPMVERIFY_MTIME')
+ if vflags & RPMVERIFY_MODE:
+ print('RPMVERIFY_MODE')
+ if vflags & RPMVERIFY_RDEV:
+ print('RPMVERIFY_RDEV')
+ if vflags & RPMVERIFY_CONTEXTS:
+ print('RPMVERIFY_CONTEXTS')
+ if vflags & RPMVERIFY_READLINKFAIL:
+ print('RPMVERIFY_READLINKFAIL')
+ if vflags & RPMVERIFY_READFAIL:
+ print('RPMVERIFY_READFAIL')
+ if vflags & RPMVERIFY_LSTATFAIL:
+ print('RPMVERIFY_LSTATFAIL')
+ if vflags & RPMVERIFY_LGETFILECONFAIL:
+ print('RPMVERIFY_LGETFILECONFAIL')
+
+
+def debug_file_flags(fflags):
+ """
+ Decodes the file flags bits.
+ """
+ if fflags & rpm.RPMFILE_CONFIG:
+ print('rpm.RPMFILE_CONFIG')
+
+ if fflags & rpm.RPMFILE_DOC:
+ print('rpm.RPMFILE_DOC')
+
+ if fflags & rpm.RPMFILE_ICON:
+ print('rpm.RPMFILE_ICON')
+
+ if fflags & rpm.RPMFILE_MISSINGOK:
+ print('rpm.RPMFILE_MISSINGOK')
+
+ if fflags & rpm.RPMFILE_NOREPLACE:
+ print('rpm.RPMFILE_NOREPLACE')
+
+ if fflags & rpm.RPMFILE_GHOST:
+ print('rpm.RPMFILE_GHOST')
+
+ if fflags & rpm.RPMFILE_LICENSE:
+ print('rpm.RPMFILE_LICENSE')
+
+ if fflags & rpm.RPMFILE_README:
+ print('rpm.RPMFILE_README')
+
+ if fflags & rpm.RPMFILE_EXCLUDE:
+ print('rpm.RPMFILE_EXLUDE')
+
+ if fflags & rpm.RPMFILE_UNPATCHED:
+ print('rpm.RPMFILE_UNPATCHED')
+
+ if fflags & rpm.RPMFILE_PUBKEY:
+ print('rpm.RPMFILE_PUBKEY')
+
+
+def rpm_verify_file(fileinfo, rpmlinktos, omitmask):
+ """
+ Verify all the files in a package.
+
+ Returns a list of error flags, the file type and file name. The list
+ entries are strings that are the same as the labels for the bitwise
+ flags used in the C code.
+
+ """
+ (fname, fsize, fmode, fmtime, fflags, frdev, finode, fnlink, fstate,
+ vflags, fuser, fgroup, fmd5) = fileinfo
+
+ # 1. rpmtsRootDir stuff. What does it do and where to I get it from?
+
+ file_results = []
+ flags = vflags
+
+ # Check to see if the file was installed - if not pretend all is ok.
+ # This is what the rpm C code does!
+ if fstate != rpm.RPMFILE_STATE_NORMAL:
+ return file_results
+
+ # Get the installed files stats
+ try:
+ lstat = os.lstat(fname)
+ except OSError:
+ if not (fflags & (rpm.RPMFILE_MISSINGOK | rpm.RPMFILE_GHOST)):
+ file_results.append('RPMVERIFY_LSTATFAIL')
+ #file_results.append(fname)
+ return file_results
+
+ # 5. Contexts? SELinux stuff?
+
+ # Setup what checks to do. This is straight out of the C code.
+ if stat.S_ISDIR(lstat.st_mode):
+ flags &= DIR_FLAGS
+ elif stat.S_ISLNK(lstat.st_mode):
+ flags &= LINK_FLAGS
+ elif stat.S_ISFIFO(lstat.st_mode):
+ flags &= FIFO_FLAGS
+ elif stat.S_ISCHR(lstat.st_mode):
+ flags &= CHR_FLAGS
+ elif stat.S_ISBLK(lstat.st_mode):
+ flags &= BLK_FLAGS
+ else:
+ flags &= REG_FLAGS
+
+ if (fflags & rpm.RPMFILE_GHOST):
+ flags &= GHOST_FLAGS
+
+ flags &= ~(omitmask | RPMVERIFY_FAILURES)
+
+ # 8. SELinux stuff.
+
+ prelink_size = 0
+ if flags & RPMVERIFY_MD5:
+ prelink_md5, prelink_size = prelink_md5_check(fname)
+ if prelink_md5 is False:
+ file_results.append('RPMVERIFY_MD5')
+ file_results.append('RPMVERIFY_READFAIL')
+ elif prelink_md5 != fmd5:
+ file_results.append('RPMVERIFY_MD5')
+
+ if flags & RPMVERIFY_LINKTO:
+ linkto = os.readlink(fname)
+ if not linkto:
+ file_results.append('RPMVERIFY_READLINKFAIL')
+ file_results.append('RPMVERIFY_LINKTO')
+ else:
+ if len(rpmlinktos) == 0 or linkto != rpmlinktos:
+ file_results.append('RPMVERIFY_LINKTO')
+
+ if flags & RPMVERIFY_FILESIZE:
+ if not (flags & RPMVERIFY_MD5): # prelink check hasn't been done.
+ prelink_size = prelink_size_check(fname)
+ if (prelink_size != 0): # This is a prelinked file.
+ if (prelink_size != fsize):
+ file_results.append('RPMVERIFY_FILESIZE')
+ elif lstat.st_size != fsize: # It wasn't a prelinked file.
+ file_results.append('RPMVERIFY_FILESIZE')
+
+ if flags & RPMVERIFY_MODE:
+ metamode = fmode
+ filemode = lstat.st_mode
+
+ # Comparing the type of %ghost files is meaningless, but perms are ok.
+ if fflags & rpm.RPMFILE_GHOST:
+ metamode &= ~0xf000
+ filemode &= ~0xf000
+
+ if (stat.S_IFMT(metamode) != stat.S_IFMT(filemode)) or \
+ (stat.S_IMODE(metamode) != stat.S_IMODE(filemode)):
+ file_results.append('RPMVERIFY_MODE')
+
+ if flags & RPMVERIFY_RDEV:
+ if (stat.S_ISCHR(fmode) != stat.S_ISCHR(lstat.st_mode) or
+ stat.S_ISBLK(fmode) != stat.S_ISBLK(lstat.st_mode)):
+ file_results.append('RPMVERIFY_RDEV')
+ elif (s_isdev(fmode) & s_isdev(lstat.st_mode)):
+ st_rdev = lstat.st_rdev
+ if frdev != st_rdev:
+ file_results.append('RPMVERIFY_RDEV')
+
+ if flags & RPMVERIFY_MTIME:
+ if lstat.st_mtime != fmtime:
+ file_results.append('RPMVERIFY_MTIME')
+
+ if flags & RPMVERIFY_USER:
+ try:
+ user = pwd.getpwuid(lstat.st_uid)[0]
+ except KeyError:
+ user = None
+ if not user or not fuser or (user != fuser):
+ file_results.append('RPMVERIFY_USER')
+
+ if flags & RPMVERIFY_GROUP:
+ try:
+ group = grp.getgrgid(lstat.st_gid)[0]
+ except KeyError:
+ group = None
+ if not group or not fgroup or (group != fgroup):
+ file_results.append('RPMVERIFY_GROUP')
+
+ return file_results
+
+
+def rpm_verify_dependencies(header):
+ """
+ Check package dependencies. Header is an rpm.hdr.
+
+ Don't like opening another ts to do this, but
+ it was the only way I could find of clearing the ts
+ out.
+
+ Have asked on the rpm-maint list on how to do
+ this the right way (28 Feb 2007).
+
+ ts.check() returns:
+
+ ((name, version, release), (reqname, reqversion), \
+ flags, suggest, sense)
+
+ """
+ _ts1 = rpmtransactionset()
+ _ts1.addInstall(header, 'Dep Check', 'i')
+ dep_errors = _ts1.check()
+ _ts1.closeDB()
+ return dep_errors
+
+
+def rpm_verify_package(vp_ts, header, verify_options):
+ """
+ Verify a single package specified by header. Header is an rpm.hdr.
+
+ If errors are found it returns a dictionary of errors.
+
+ """
+ # Set some transaction level flags.
+ vsflags = 0
+ if 'nodigest' in verify_options:
+ vsflags |= rpm._RPMVSF_NODIGESTS
+ if 'nosignature' in verify_options:
+ vsflags |= rpm._RPMVSF_NOSIGNATURES
+ ovsflags = vp_ts.setVSFlags(vsflags)
+
+ # Map from the Python options to the rpm bitwise flags.
+ omitmask = 0
+
+ if 'nolinkto' in verify_options:
+ omitmask |= VERIFY_LINKTO
+ if 'nomd5' in verify_options:
+ omitmask |= VERIFY_MD5
+ if 'nosize' in verify_options:
+ omitmask |= VERIFY_SIZE
+ if 'nouser' in verify_options:
+ omitmask |= VERIFY_USER
+ if 'nogroup' in verify_options:
+ omitmask |= VERIFY_GROUP
+ if 'nomtime' in verify_options:
+ omitmask |= VERIFY_MTIME
+ if 'nomode' in verify_options:
+ omitmask |= VERIFY_MODE
+ if 'nordev' in verify_options:
+ omitmask |= VERIFY_RDEV
+
+ omitmask = ((~omitmask & VERIFY_ATTRS) ^ VERIFY_ATTRS)
+
+ package_results = {}
+
+ # Check Signatures and Digests.
+ # No idea what this might return. Need to break something to see.
+ # Setting the vsflags above determines what gets checked in the header.
+ hdr_stat = vp_ts.hdrCheck(header.unload())
+ if hdr_stat:
+ package_results['hdr'] = hdr_stat
+
+ # Check Package Depencies.
+ if 'nodeps' not in verify_options:
+ dep_stat = rpm_verify_dependencies(header)
+ if dep_stat:
+ package_results['deps'] = dep_stat
+
+ # Check all the package files.
+ if 'nofiles' not in verify_options:
+ vp_fi = header.fiFromHeader()
+ for fileinfo in vp_fi:
+ # Do not bother doing anything with ghost files.
+ # This is what RPM does.
+ if fileinfo[4] & rpm.RPMFILE_GHOST:
+ continue
+
+ # This is only needed because of an inconsistency in the
+ # rpm.fi interface.
+ linktos = vp_fi.FLink()
+
+ file_stat = rpm_verify_file(fileinfo, linktos, omitmask)
+
+ #if len(file_stat) > 0 or options.verbose:
+ if len(file_stat) > 0:
+ fflags = fileinfo[4]
+ if fflags & rpm.RPMFILE_CONFIG:
+ file_stat.append('c')
+ elif fflags & rpm.RPMFILE_DOC:
+ file_stat.append('d')
+ elif fflags & rpm.RPMFILE_GHOST:
+ file_stat.append('g')
+ elif fflags & rpm.RPMFILE_LICENSE:
+ file_stat.append('l')
+ elif fflags & rpm.RPMFILE_PUBKEY:
+ file_stat.append('P')
+ elif fflags & rpm.RPMFILE_README:
+ file_stat.append('r')
+ else:
+ file_stat.append(' ')
+
+ file_stat.append(fileinfo[0]) # The filename.
+ package_results.setdefault('files', []).append(file_stat)
+
+ # Run the verify script if there is one.
+ # Do we want this?
+ #if 'noscripts' not in verify_options:
+ # script_stat = rpmVerifyscript()
+ # if script_stat:
+ # package_results['script'] = script_stat
+
+ # If there have been any errors, add the package nevra to the result.
+ if len(package_results) > 0:
+ package_results.setdefault('nevra', (header[rpm.RPMTAG_NAME],
+ header[rpm.RPMTAG_EPOCH],
+ header[rpm.RPMTAG_VERSION],
+ header[rpm.RPMTAG_RELEASE],
+ header[rpm.RPMTAG_ARCH]))
+ else:
+ package_results = None
+
+ # Put things back the way we found them.
+ vsflags = vp_ts.setVSFlags(ovsflags)
+
+ return package_results
+
+
+def rpm_verify(verify_ts, verify_pkgspec, verify_options=[]):
+ """
+ Requires rpmtransactionset() to be run first to get a ts.
+
+ pkgspec is a dict specifying the package
+ e.g.:
+ For a single package
+ { name='foo', epoch='20', version='1', release='1', arch='x86_64'}
+
+ For all packages
+ {}
+
+ Or any combination of keywords to select one or more packages to verify.
+
+ options is a list of 'rpm --verify' options.
+ Default is to check everything.
+ e.g.:
+ [ 'nodeps', 'nodigest', 'nofiles', 'noscripts', 'nosignature',
+ 'nolinkto' 'nomd5', 'nosize', 'nouser', 'nogroup', 'nomtime',
+ 'nomode', 'nordev' ]
+
+ Returns a list. One list entry per package. Each list entry is a
+ dictionary. Dict keys are 'files', 'deps', 'nevra' and 'hdr'.
+ Entries only get added for the failures. If nothing failed, None is
+ returned.
+
+ Its all a bit messy and probably needs reviewing.
+
+ [ { 'hdr': [???],
+ 'deps: [((name, version, release), (reqname, reqversion),
+ flags, suggest, sense), .... ]
+ 'files': [ ['filename1', 'RPMVERIFY_GROUP', 'RPMVERIFY_USER' ],
+ ['filename2', 'RPMVERFIY_LSTATFAIL']]
+ 'nevra': ['name1', 'epoch1', 'version1', 'release1', 'arch1'] }
+ { 'hdr': [???],
+ 'deps: [((name, version, release), (reqname, reqversion),
+ flags, suggest, sense), .... ]
+ 'files': [ ['filename', 'RPMVERIFY_GROUP', 'RPMVERIFY_USER" ],
+ ['filename2', 'RPMVERFIY_LSTATFAIL']]
+ 'nevra': ['name2', 'epoch2', 'version2', 'release2', 'arch2'] } ]
+
+ """
+ verify_results = []
+ headers = getheadersbykeyword(verify_ts, **verify_pkgspec)
+ for header in headers:
+ result = rpm_verify_package(verify_ts, header, verify_options)
+ if result:
+ verify_results.append(result)
+
+ return verify_results
+
+
+def rpmtransactionset():
+ """
+ A simple wrapper for rpm.TransactionSet() to keep everthiing together.
+ Might use it to set some ts level flags later.
+
+ """
+ ts = rpm.TransactionSet()
+ return ts
+
+
+class Rpmtscallback(object):
+ """
+ Callback for ts.run(). Used for adding, upgrading and removing packages.
+ Starting with all possible reasons codes, but bcfg2 will probably only
+ make use of a few of them.
+
+ Mostly just printing stuff at the moment to understand how the callback
+ is used.
+ """
+ def __init__(self):
+ self.fdnos = {}
+
+ def callback(self, reason, amount, total, key, client_data):
+ """
+ Generic rpmts call back.
+ """
+ if reason == rpm.RPMCALLBACK_INST_OPEN_FILE:
+ pass
+ elif reason == rpm.RPMCALLBACK_INST_CLOSE_FILE:
+ pass
+ elif reason == rpm.RPMCALLBACK_INST_START:
+ pass
+ elif reason == rpm.RPMCALLBACK_TRANS_PROGRESS or \
+ reason == rpm.RPMCALLBACK_INST_PROGRESS:
+ pass
+ # rpm.RPMCALLBACK_INST_PROGRESS'
+ elif reason == rpm.RPMCALLBACK_TRANS_START:
+ pass
+ elif reason == rpm.RPMCALLBACK_TRANS_STOP:
+ pass
+ elif reason == rpm.RPMCALLBACK_REPACKAGE_START:
+ pass
+ elif reason == rpm.RPMCALLBACK_REPACKAGE_PROGRESS:
+ pass
+ elif reason == rpm.RPMCALLBACK_REPACKAGE_STOP:
+ pass
+ elif reason == rpm.RPMCALLBACK_UNINST_PROGRESS:
+ pass
+ elif reason == rpm.RPMCALLBACK_UNINST_START:
+ pass
+ elif reason == rpm.RPMCALLBACK_UNINST_STOP:
+ pass
+ # How do we get at this?
+ # RPM.modified += key
+ elif reason == rpm.RPMCALLBACK_UNPACK_ERROR:
+ pass
+ elif reason == rpm.RPMCALLBACK_CPIO_ERROR:
+ pass
+ elif reason == rpm.RPMCALLBACK_UNKNOWN:
+ pass
+ else:
+ print('ERROR - Fell through callBack')
+
+
+def rpm_erase(erase_pkgspecs, erase_flags):
+ """
+ pkgspecs is a list of pkgspec dicts specifying packages
+ e.g.:
+ For a single package
+ { name='foo', epoch='20', version='1', release='1', arch='x86_64'}
+
+ """
+ erase_ts_flags = 0
+ if 'noscripts' in erase_flags:
+ erase_ts_flags |= rpm.RPMTRANS_FLAG_NOSCRIPTS
+ if 'notriggers' in erase_flags:
+ erase_ts_flags |= rpm.RPMTRANS_FLAG_NOTRIGGERS
+ if 'repackage' in erase_flags:
+ erase_ts_flags |= rpm.RPMTRANS_FLAG_REPACKAGE
+
+ erase_ts = rpmtransactionset()
+ erase_ts.setFlags(erase_ts_flags)
+
+ for pkgspec in erase_pkgspecs:
+ idx_list = getindexbykeyword(erase_ts, **pkgspec)
+ if len(idx_list) > 1 and not 'allmatches' in erase_flags:
+ #pass
+ print('ERROR - Multiple package match for erase', pkgspec)
+ else:
+ for idx in idx_list:
+ erase_ts.addErase(idx)
+
+ #for te in erase_ts:
+
+ erase_problems = []
+ if 'nodeps' not in erase_flags:
+ erase_problems = erase_ts.check()
+
+ if erase_problems == []:
+ erase_ts.order()
+ erase_callback = Rpmtscallback()
+ erase_ts.run(erase_callback.callback, 'Erase')
+ #else:
+
+ erase_ts.closeDB()
+ del erase_ts
+ return erase_problems
+
+
+def display_verify_file(file_results):
+ '''
+ Display file results similar to rpm --verify.
+ '''
+ filename = file_results[-1]
+ filetype = file_results[-2]
+
+ result_string = ''
+
+ if 'RPMVERIFY_LSTATFAIL' in file_results:
+ result_string = 'missing '
+ else:
+ if 'RPMVERIFY_FILESIZE' in file_results:
+ result_string = result_string + 'S'
+ else:
+ result_string = result_string + '.'
+
+ if 'RPMVERIFY_MODE' in file_results:
+ result_string = result_string + 'M'
+ else:
+ result_string = result_string + '.'
+
+ if 'RPMVERIFY_MD5' in file_results:
+ if 'RPMVERIFY_READFAIL' in file_results:
+ result_string = result_string + '?'
+ else:
+ result_string = result_string + '5'
+ else:
+ result_string = result_string + '.'
+
+ if 'RPMVERIFY_RDEV' in file_results:
+ result_string = result_string + 'D'
+ else:
+ result_string = result_string + '.'
+
+ if 'RPMVERIFY_LINKTO' in file_results:
+ if 'RPMVERIFY_READLINKFAIL' in file_results:
+ result_string = result_string + '?'
+ else:
+ result_string = result_string + 'L'
+ else:
+ result_string = result_string + '.'
+
+ if 'RPMVERIFY_USER' in file_results:
+ result_string = result_string + 'U'
+ else:
+ result_string = result_string + '.'
+
+ if 'RPMVERIFY_GROUP' in file_results:
+ result_string = result_string + 'G'
+ else:
+ result_string = result_string + '.'
+
+ if 'RPMVERIFY_MTIME' in file_results:
+ result_string = result_string + 'T'
+ else:
+ result_string = result_string + '.'
+
+ print(result_string + ' ' + filetype + ' ' + filename)
+ sys.stdout.flush()
+
+#=============================================================================
+# Some options and output to assist with development and testing.
+# These are not intended for normal use.
+if __name__ == "__main__":
+
+ p = optparse.OptionParser()
+
+ p.add_option('--name', action='store',
+ default=None,
+ help='''Package name to verify.
+
+ ******************************************
+ NOT SPECIFYING A NAME MEANS 'ALL' PACKAGES.
+ ******************************************
+
+ The specified operation will be carried out on all
+ instances of packages that match the package
+ specification
+ (name, epoch, version, release, arch).''')
+
+ p.add_option('--epoch', action='store',
+ default=None,
+ help='''Package epoch.''')
+
+ p.add_option('--version', action='store',
+ default=None,
+ help='''Package version.''')
+
+ p.add_option('--release', action='store',
+ default=None,
+ help='''Package release.''')
+
+ p.add_option('--arch', action='store',
+ default=None,
+ help='''Package arch.''')
+
+ p.add_option('--erase', '-e', action='store_true',
+ default=None,
+ help=
+ '''****************************************************
+ REMOVE PACKAGES. THERE ARE NO WARNINGS. MULTIPLE
+ PACKAGES WILL BE REMOVED IF A FULL PACKAGE SPEC IS NOT
+ GIVEN. E.G. IF JUST A NAME IS GIVEN ALL INSTALLED
+ INSTANCES OF THAT PACKAGE WILL BE REMOVED PROVIDED
+ DEPENDENCY CHECKS PASS. IF JUST AN EPOCH IS GIVEN
+ ALL PACKAGE INSTANCES WITH THAT EPOCH WILL BE REMOVED.
+ ****************************************************''')
+
+ p.add_option('--list', '-l', action='store_true',
+ help='''List package identity info. rpm -qa ish equivalent
+ intended for use in RefreshPackages().''')
+
+ p.add_option('--verify', action='store_true',
+ help='''Verify Package(s). Output is only produced after all
+ packages has been verified. Be patient.''')
+
+ p.add_option('--verbose', '-v', action='store_true',
+ help='''Verbose output for --verify option. Output is the
+ same as rpm -v --verify.''')
+
+ p.add_option('--nodeps', action='store_true',
+ default=False,
+ help='Do not do dependency testing.')
+
+ p.add_option('--nodigest', action='store_true',
+ help='Do not check package digests.')
+
+ p.add_option('--nofiles', action='store_true',
+ help='Do not do file checks.')
+
+ p.add_option('--noscripts', action='store_true',
+ help='Do not run verification scripts.')
+
+ p.add_option('--nosignature', action='store_true',
+ help='Do not do package signature verification.')
+
+ p.add_option('--nolinkto', action='store_true',
+ help='Do not do symlink tests.')
+
+ p.add_option('--nomd5', action='store_true',
+ help='''Do not do MD5 checksums on files. Note that this does
+ not work for prelink files yet.''')
+
+ p.add_option('--nosize', action='store_true',
+ help='''Do not do file size tests. Note that this does not
+ work for prelink files yet.''')
+
+ p.add_option('--nouser', action='store_true',
+ help='Do not check file user ownership.')
+
+ p.add_option('--nogroup', action='store_true',
+ help='Do not check file group ownership.')
+
+ p.add_option('--nomtime', action='store_true',
+ help='Do not check file modification times.')
+
+ p.add_option('--nomode', action='store_true',
+ help='Do not check file modes (permissions).')
+
+ p.add_option('--nordev', action='store_true',
+ help='Do not check device node.')
+
+ p.add_option('--notriggers', action='store_true',
+ help='Do not do not generate triggers on erase.')
+
+ p.add_option('--repackage', action='store_true',
+ help='''Do repackage on erase.i Packages are put
+ in /var/spool/repackage.''')
+
+ p.add_option('--allmatches', action='store_true',
+ help=
+ '''Remove all package instances that match the
+ pkgspec.
+
+ ***************************************************
+ NO WARNINGS ARE GIVEN. IF THERE IS NO PACKAGE SPEC
+ THAT MEANS ALL PACKAGES!!!!
+ ***************************************************''')
+
+ options, arguments = p.parse_args()
+
+ pkgspec = {}
+ rpm_options = []
+
+ if options.nodeps:
+ rpm_options.append('nodeps')
+
+ if options.nodigest:
+ rpm_options.append('nodigest')
+
+ if options.nofiles:
+ rpm_options.append('nofiles')
+
+ if options.noscripts:
+ rpm_options.append('noscripts')
+
+ if options.nosignature:
+ rpm_options.append('nosignature')
+
+ if options.nolinkto:
+ rpm_options.append('nolinkto')
+
+ if options.nomd5:
+ rpm_options.append('nomd5')
+
+ if options.nosize:
+ rpm_options.append('nosize')
+
+ if options.nouser:
+ rpm_options.append('nouser')
+
+ if options.nogroup:
+ rpm_options.append('nogroup')
+
+ if options.nomtime:
+ rpm_options.append('nomtime')
+
+ if options.nomode:
+ rpm_options.append('nomode')
+
+ if options.nordev:
+ rpm_options.append('nordev')
+
+ if options.repackage:
+ rpm_options.append('repackage')
+
+ if options.allmatches:
+ rpm_options.append('allmatches')
+
+ main_ts = rpmtransactionset()
+
+ cmdline_pkgspec = {}
+ if options.name != 'all':
+ if options.name:
+ cmdline_pkgspec['name'] = str(options.name)
+ if options.epoch:
+ cmdline_pkgspec['epoch'] = str(options.epoch)
+ if options.version:
+ cmdline_pkgspec['version'] = str(options.version)
+ if options.release:
+ cmdline_pkgspec['release'] = str(options.release)
+ if options.arch:
+ cmdline_pkgspec['arch'] = str(options.arch)
+
+ if options.verify:
+ results = rpm_verify(main_ts, cmdline_pkgspec, rpm_options)
+ for r in results:
+ files = r.get('files', '')
+ for f in files:
+ display_verify_file(f)
+
+ elif options.list:
+ for p in rpmpackagelist(main_ts):
+ print(p)
+
+ elif options.erase:
+ if options.name:
+ rpm_erase([cmdline_pkgspec], rpm_options)
+ else:
+ print('You must specify the "--name" option')
+
class RPM(Bcfg2.Client.Tools.PkgTool):
"""Support for RPM packages."""
+ options = Bcfg2.Client.Tools.PkgTool.options + [
+ Bcfg2.Options.Option(
+ cf=('RPM', 'installonlypackages'), dest="rpm_installonly",
+ type=Bcfg2.Options.Types.comma_list,
+ default=['kernel', 'kernel-bigmem', 'kernel-enterprise',
+ 'kernel-smp', 'kernel-modules', 'kernel-debug',
+ 'kernel-unsupported', 'kernel-devel', 'kernel-source',
+ 'kernel-default', 'kernel-largesmp-devel',
+ 'kernel-largesmp', 'kernel-xen', 'gpg-pubkey'],
+ help='RPM install-only packages'),
+ Bcfg2.Options.BooleanOption(
+ cf=('RPM', 'pkg_checks'), default=True, dest="rpm_pkg_checks",
+ help="Perform RPM package checks"),
+ Bcfg2.Options.BooleanOption(
+ cf=('RPM', 'pkg_verify'), default=True, dest="rpm_pkg_verify",
+ help="Perform RPM package verify"),
+ Bcfg2.Options.BooleanOption(
+ cf=('RPM', 'install_missing'), default=True,
+ dest="rpm_install_missing",
+ help="Install missing packages"),
+ Bcfg2.Options.Option(
+ cf=('RPM', 'erase_flags'), default=["allmatches"],
+ dest="rpm_erase_flags", type=Bcfg2.Options.Types.comma_list,
+ help="RPM erase flags"),
+ Bcfg2.Options.BooleanOption(
+ cf=('RPM', 'fix_version'), default=True,
+ dest="rpm_fix_version",
+ help="Fix (upgrade or downgrade) packages with the wrong version"),
+ Bcfg2.Options.BooleanOption(
+ cf=('RPM', 'reinstall_broken'), default=True,
+ dest="rpm_reinstall_broken",
+ help="Reinstall packages that fail to verify"),
+ Bcfg2.Options.Option(
+ cf=('RPM', 'verify_flags'), default=[],
+ dest="rpm_verify_flags", type=Bcfg2.Options.Types.comma_list,
+ help="RPM verify flags")]
+
__execs__ = ['/bin/rpm', '/var/lib/rpm']
__handles__ = [('Package', 'rpm')]
@@ -15,7 +1143,7 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
__new_req__ = {'Package': ['name'],
'Instance': ['version', 'release', 'arch']}
- __new_ireq__ = {'Package': ['uri'], \
+ __new_ireq__ = {'Package': ['uri'],
'Instance': ['simplefile']}
__gpg_req__ = {'Package': ['name', 'version']}
@@ -26,60 +1154,51 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
__new_gpg_ireq__ = {'Package': ['name'],
'Instance': ['version', 'release']}
- conflicts = ['RPMng']
-
pkgtype = 'rpm'
pkgtool = ("rpm --oldpackage --replacepkgs --quiet -U %s", ("%s", ["url"]))
- def __init__(self, logger, setup, config):
- Bcfg2.Client.Tools.PkgTool.__init__(self, logger, setup, config)
+ def __init__(self, config):
+ Bcfg2.Client.Tools.PkgTool.__init__(self, config)
# create a global ignore list used when ignoring particular
# files during package verification
- self.ignores = [entry.get('name') for struct in config for entry in struct \
- if entry.get('type') == 'ignore']
+ self.ignores = [entry.get('name') for struct in config
+ for entry in struct if entry.get('type') == 'ignore']
self.instance_status = {}
self.extra_instances = []
self.modlists = {}
self.gpg_keyids = self.getinstalledgpg()
- opt_prefix = self.name.lower()
- self.installOnlyPkgs = self.setup["%s_installonly" % opt_prefix]
+ self.installOnlyPkgs = Bcfg2.Options.setup.rpm_installonly
if 'gpg-pubkey' not in self.installOnlyPkgs:
self.installOnlyPkgs.append('gpg-pubkey')
- self.erase_flags = self.setup['%s_erase_flags' % opt_prefix]
- self.pkg_checks = self.setup['%s_pkg_checks' % opt_prefix]
- self.pkg_verify = self.setup['%s_pkg_verify' % opt_prefix]
- self.installed_action = self.setup['%s_installed_action' % opt_prefix]
- self.version_fail_action = self.setup['%s_version_fail_action' %
- opt_prefix]
- self.verify_fail_action = self.setup['%s_verify_fail_action' %
- opt_prefix]
- self.verify_flags = self.setup['%s_verify_flags' % opt_prefix]
+ self.verify_flags = Bcfg2.Options.setup.rpm_verify_flags
if '' in self.verify_flags:
self.verify_flags.remove('')
self.logger.debug('%s: installOnlyPackages = %s' %
(self.name, self.installOnlyPkgs))
self.logger.debug('%s: erase_flags = %s' %
- (self.name, self.erase_flags))
+ (self.name, Bcfg2.Options.setup.rpm_erase_flags))
self.logger.debug('%s: pkg_checks = %s' %
- (self.name, self.pkg_checks))
+ (self.name, Bcfg2.Options.setup.rpm_pkg_checks))
self.logger.debug('%s: pkg_verify = %s' %
- (self.name, self.pkg_verify))
- self.logger.debug('%s: installed_action = %s' %
- (self.name, self.installed_action))
- self.logger.debug('%s: version_fail_action = %s' %
- (self.name, self.version_fail_action))
- self.logger.debug('%s: verify_fail_action = %s' %
- (self.name, self.verify_fail_action))
+ (self.name, Bcfg2.Options.setup.rpm_pkg_verify))
+ self.logger.debug('%s: install_missing = %s' %
+ (self.name, Bcfg2.Options.setup.install_missing))
+ self.logger.debug('%s: fix_version = %s' %
+ (self.name, Bcfg2.Options.setup.rpm_fix_version))
+ self.logger.debug('%s: reinstall_broken = %s' %
+ (self.name,
+ Bcfg2.Options.setup.rpm_reinstall_broken))
self.logger.debug('%s: verify_flags = %s' %
(self.name, self.verify_flags))
# Force a re- prelink of all packages if prelink exists.
# Many, if not most package verifies can be caused by out of
# date prelinking.
- if os.path.isfile('/usr/sbin/prelink') and not self.setup['dryrun']:
+ if (os.path.isfile('/usr/sbin/prelink') and
+ not Bcfg2.Options.setup.dry_run):
rv = self.cmd.run('/usr/sbin/prelink -a -mR')
if rv.success:
self.logger.debug('Pre-emptive prelink succeeded')
@@ -104,18 +1223,18 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
'arch':'x86_64'} ]
"""
self.installed = {}
- refresh_ts = rpmtools.rpmtransactionset()
+ refresh_ts = rpmtransactionset()
# Don't bother with signature checks at this stage. The GPG keys might
# not be installed.
- refresh_ts.setVSFlags(rpm._RPMVSF_NODIGESTS|rpm._RPMVSF_NOSIGNATURES)
- for nevra in rpmtools.rpmpackagelist(refresh_ts):
+ refresh_ts.setVSFlags(rpm._RPMVSF_NODIGESTS | rpm._RPMVSF_NOSIGNATURES)
+ for nevra in rpmpackagelist(refresh_ts):
self.installed.setdefault(nevra['name'], []).append(nevra)
- if self.setup['debug']:
+ if Bcfg2.Options.setup.debug:
print("The following package instances are installed:")
for name, instances in list(self.installed.items()):
self.logger.debug(" " + name)
for inst in instances:
- self.logger.debug(" %s" %self.str_evra(inst))
+ self.logger.debug(" %s" % self.str_evra(inst))
refresh_ts.closeDB()
del refresh_ts
@@ -145,18 +1264,19 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
Constructs the text prompts for interactive mode.
"""
- instances = [inst for inst in entry if inst.tag == 'Instance' or inst.tag == 'Package']
+ instances = [inst for inst in entry if inst.tag == 'Instance' or
+ inst.tag == 'Package']
if instances == []:
# We have an old style no Instance entry. Convert it to new style.
instance = Bcfg2.Client.XML.SubElement(entry, 'Package')
for attrib in list(entry.attrib.keys()):
instance.attrib[attrib] = entry.attrib[attrib]
- if (self.pkg_checks and
- entry.get('pkg_checks', 'true').lower() == 'true'):
+ if (Bcfg2.Options.setup.rpm_pkg_checks and
+ entry.get('pkg_checks', 'true').lower() == 'true'):
if 'any' in [entry.get('version'), pinned_version]:
version, release = 'any', 'any'
elif entry.get('version') == 'auto':
- if pinned_version != None:
+ if pinned_version is not None:
version, release = pinned_version.split('-')
else:
return False
@@ -166,242 +1286,315 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
instance.set('release', release)
if entry.get('verify', 'true') == 'false':
instance.set('verify', 'false')
- instances = [ instance ]
+ instances = [instance]
- self.logger.debug("Verifying package instances for %s" % entry.get('name'))
+ self.logger.debug("Verifying package instances for %s" %
+ entry.get('name'))
package_fail = False
qtext_versions = ''
if entry.get('name') in self.installed:
# There is at least one instance installed.
- if (self.pkg_checks and
- entry.get('pkg_checks', 'true').lower() == 'true'):
+ if (Bcfg2.Options.setup.rpm_pkg_checks and
+ entry.get('pkg_checks', 'true').lower() == 'true'):
rpmTs = rpm.TransactionSet()
rpmHeader = None
for h in rpmTs.dbMatch(rpm.RPMTAG_NAME, entry.get('name')):
- if rpmHeader is None or rpm.versionCompare(h, rpmHeader) > 0:
+ if rpmHeader is None or \
+ rpm.versionCompare(h, rpmHeader) > 0:
rpmHeader = h
- rpmProvides = [ h['provides'] for h in \
- rpmTs.dbMatch(rpm.RPMTAG_NAME, entry.get('name')) ]
+ rpmProvides = [h['provides'] for h in
+ rpmTs.dbMatch(rpm.RPMTAG_NAME,
+ entry.get('name'))]
rpmIntersection = set(rpmHeader['provides']) & \
- set(self.installOnlyPkgs)
+ set(self.installOnlyPkgs)
if len(rpmIntersection) > 0:
# Packages that should only be installed or removed.
# e.g. kernels.
self.logger.debug(" Install only package.")
for inst in instances:
- self.instance_status.setdefault(inst, {})['installed'] = False
+ self.instance_status.setdefault(inst, {})['installed']\
+ = False
self.instance_status[inst]['version_fail'] = False
- if inst.tag == 'Package' and len(self.installed[entry.get('name')]) > 1:
- self.logger.error("WARNING: Multiple instances of package %s are installed." % \
+ if inst.tag == 'Package' and \
+ len(self.installed[entry.get('name')]) > 1:
+ self.logger.error("WARNING: Multiple instances of "
+ "package %s are installed." %
(entry.get('name')))
for pkg in self.installed[entry.get('name')]:
- if inst.get('version') == 'any' or self.pkg_vr_equal(inst, pkg) \
- or self.inst_evra_equal(inst, pkg):
+ if inst.get('version') == 'any' or \
+ self.pkg_vr_equal(inst, pkg) or \
+ self.inst_evra_equal(inst, pkg):
if inst.get('version') == 'any':
self.logger.error("got any version")
- self.logger.debug(" %s" % self.str_evra(inst))
+ self.logger.debug(" %s" %
+ self.str_evra(inst))
self.instance_status[inst]['installed'] = True
- if (self.pkg_verify and
- inst.get('pkg_verify', 'true').lower() == 'true'):
- flags = inst.get('verify_flags', '').split(',') + self.verify_flags
+ if (Bcfg2.Options.setup.rpm_pkg_verify and
+ inst.get('pkg_verify',
+ 'true').lower() == 'true'):
+ flags = inst.get('verify_flags',
+ '').split(',') + \
+ self.verify_flags
if pkg.get('gpgkeyid', '')[-8:] not in self.gpg_keyids and \
entry.get('name') != 'gpg-pubkey':
flags += ['nosignature', 'nodigest']
- self.logger.debug('WARNING: Package %s %s requires GPG Public key with ID %s'\
- % (pkg.get('name'), self.str_evra(pkg), \
- pkg.get('gpgkeyid', '')))
- self.logger.debug(' Disabling signature check.')
-
- if self.setup.get('quick', False):
- if rpmtools.prelink_exists:
+ self.logger.debug('WARNING: Package '
+ '%s %s requires GPG '
+ 'Public key with ID '
+ '%s' %
+ (pkg.get('name'),
+ self.str_evra(pkg),
+ pkg.get('gpgkeyid',
+ '')))
+ self.logger.debug(' Disabling '
+ 'signature check.')
+
+ if Bcfg2.Options.setup.quick:
+ if prelink_exists:
flags += ['nomd5', 'nosize']
else:
flags += ['nomd5']
- self.logger.debug(" verify_flags = %s" % flags)
+ self.logger.debug(" verify_flags = "
+ "%s" % flags)
if inst.get('verify', 'true') == 'false':
- self.instance_status[inst]['verify'] = None
+ self.instance_status[inst]['verify'] =\
+ None
else:
- vp_ts = rpmtools.rpmtransactionset()
- self.instance_status[inst]['verify'] = \
- rpmtools.rpm_verify( vp_ts, pkg, flags)
+ vp_ts = rpmtransactionset()
+ self.instance_status[inst]['verify'] =\
+ rpm_verify(vp_ts, pkg, flags)
vp_ts.closeDB()
del vp_ts
- if self.instance_status[inst]['installed'] == False:
- self.logger.info(" Package %s %s not installed." % \
- (entry.get('name'), self.str_evra(inst)))
+ if not self.instance_status[inst]['installed']:
+ self.logger.info(" Package %s %s not "
+ "installed." %
+ (entry.get('name'),
+ self.str_evra(inst)))
- qtext_versions = qtext_versions + 'I(%s) ' % self.str_evra(inst)
+ qtext_versions = qtext_versions + 'I(%s) ' % \
+ self.str_evra(inst)
entry.set('current_exists', 'false')
else:
# Normal Packages that can be upgraded.
for inst in instances:
- self.instance_status.setdefault(inst, {})['installed'] = False
+ self.instance_status.setdefault(inst, {})['installed']\
+ = False
self.instance_status[inst]['version_fail'] = False
- # Only installed packages with the same architecture are
- # relevant.
- if inst.get('arch', None) == None:
+ # only installed packages with the same architecture
+ # are relevant.
+ if inst.get('arch', None) is None:
arch_match = self.installed[entry.get('name')]
else:
- arch_match = [pkg for pkg in self.installed[entry.get('name')] \
- if pkg.get('arch', None) == inst.get('arch', None)]
+ arch_match = [pkg for pkg in
+ self.installed[entry.get('name')]
+ if pkg.get('arch', None) ==
+ inst.get('arch', None)]
if len(arch_match) > 1:
- self.logger.error("Multiple instances of package %s installed with the same achitecture." % \
- (entry.get('name')))
+ self.logger.error("Multiple instances of package "
+ "%s installed with the same "
+ "achitecture." %
+ (entry.get('name')))
elif len(arch_match) == 1:
# There is only one installed like there should be.
# Check that it is the right version.
for pkg in arch_match:
- if inst.get('version') == 'any' or self.pkg_vr_equal(inst, pkg) or \
- self.inst_evra_equal(inst, pkg):
- self.logger.debug(" %s" % self.str_evra(inst))
- self.instance_status[inst]['installed'] = True
-
- if (self.pkg_verify and
- inst.get('pkg_verify', 'true').lower() == 'true'):
- flags = inst.get('verify_flags', '').split(',') + self.verify_flags
- if pkg.get('gpgkeyid', '')[-8:] not in self.gpg_keyids and \
- 'nosignature' not in flags:
- flags += ['nosignature', 'nodigest']
- self.logger.info('WARNING: Package %s %s requires GPG Public key with ID %s'\
- % (pkg.get('name'), self.str_evra(pkg), \
- pkg.get('gpgkeyid', '')))
- self.logger.info(' Disabling signature check.')
-
- if self.setup.get('quick', False):
- if rpmtools.prelink_exists:
+ if inst.get('version') == 'any' or \
+ self.pkg_vr_equal(inst, pkg) or \
+ self.inst_evra_equal(inst, pkg):
+ self.logger.debug(" %s" %
+ self.str_evra(inst))
+ self.instance_status[inst]['installed'] = \
+ True
+
+ if (Bcfg2.Options.setup.rpm_pkg_verify and
+ inst.get(
+ 'pkg_verify',
+ 'true').lower() == 'true'):
+ flags = inst.get('verify_flags',
+ '').split(',') + \
+ self.verify_flags
+ if pkg.get('gpgkeyid', '')[-8:] not in\
+ self.gpg_keyids and 'nosignature'\
+ not in flags:
+ flags += ['nosignature',
+ 'nodigest']
+ self.logger.info(
+ 'WARNING: Package %s %s '
+ 'requires GPG Public key with '
+ 'ID %s' % (pkg.get('name'),
+ self.str_evra(pkg),
+ pkg.get('gpgkeyid',
+ '')))
+ self.logger.info(
+ ' Disabling signature '
+ 'check.')
+
+ if Bcfg2.Options.setup.quick:
+ if prelink_exists:
flags += ['nomd5', 'nosize']
else:
flags += ['nomd5']
- self.logger.debug(" verify_flags = %s" % flags)
+ self.logger.debug(
+ " verify_flags = %s" %
+ flags)
- if inst.get('verify', 'true') == 'false':
+ if inst.get('verify', 'true') == \
+ 'false':
self.instance_status[inst]['verify'] = None
else:
- vp_ts = rpmtools.rpmtransactionset()
- self.instance_status[inst]['verify'] = \
- rpmtools.rpm_verify( vp_ts, pkg, flags )
+ vp_ts = rpmtransactionset()
+ self.instance_status[inst]['verify'] = rpm_verify(vp_ts, pkg, flags)
vp_ts.closeDB()
del vp_ts
else:
# Wrong version installed.
- self.instance_status[inst]['version_fail'] = True
- self.logger.info(" Wrong version installed. Want %s, but have %s"\
- % (self.str_evra(inst), self.str_evra(pkg)))
-
- qtext_versions = qtext_versions + 'U(%s -> %s) ' % \
- (self.str_evra(pkg), self.str_evra(inst))
+ self.instance_status[inst]['version_fail']\
+ = True
+ self.logger.info(" Wrong version "
+ "installed. Want %s, but "
+ "have %s" %
+ (self.str_evra(inst),
+ self.str_evra(pkg)))
+
+ qtext_versions = qtext_versions + \
+ 'U(%s -> %s) ' % (self.str_evra(pkg),
+ self.str_evra(inst))
elif len(arch_match) == 0:
# This instance is not installed.
self.instance_status[inst]['installed'] = False
- self.logger.info(" %s is not installed." % self.str_evra(inst))
- qtext_versions = qtext_versions + 'I(%s) ' % self.str_evra(inst)
+ self.logger.info(" %s is not installed." %
+ self.str_evra(inst))
+ qtext_versions = qtext_versions + \
+ 'I(%s) ' % self.str_evra(inst)
# Check the rpm verify results.
for inst in instances:
instance_fail = False
# Dump the rpm verify results.
#****Write something to format this nicely.*****
- if self.setup['debug'] and self.instance_status[inst].get('verify', None):
+ if (Bcfg2.Options.setup.debug and
+ self.instance_status[inst].get('verify', None)):
self.logger.debug(self.instance_status[inst]['verify'])
self.instance_status[inst]['verify_fail'] = False
if self.instance_status[inst].get('verify', None):
if len(self.instance_status[inst].get('verify')) > 1:
- self.logger.info("WARNING: Verification of more than one package instance.")
+ self.logger.info("WARNING: Verification of more "
+ "than one package instance.")
for result in self.instance_status[inst]['verify']:
# Check header results
if result.get('hdr', None):
instance_fail = True
- self.instance_status[inst]['verify_fail'] = True
+ self.instance_status[inst]['verify_fail'] = \
+ True
# Check dependency results
if result.get('deps', None):
instance_fail = True
- self.instance_status[inst]['verify_fail'] = True
-
- # Check the rpm verify file results against the modlist
- # and entry and per Instance Ignores.
- ignores = [ig.get('name') for ig in entry.findall('Ignore')] + \
- [ig.get('name') for ig in inst.findall('Ignore')] + \
- self.ignores
+ self.instance_status[inst]['verify_fail'] = \
+ True
+
+ # check the rpm verify file results against
+ # the modlist and entry and per Instance Ignores.
+ ignores = [ig.get('name')
+ for ig in entry.findall('Ignore')] + \
+ [ig.get('name')
+ for ig in inst.findall('Ignore')] + \
+ self.ignores
for file_result in result.get('files', []):
if file_result[-1] not in modlist + ignores:
instance_fail = True
- self.instance_status[inst]['verify_fail'] = True
+ self.instance_status[inst]['verify_fail'] \
+ = True
else:
- self.logger.debug(" Modlist/Ignore match: %s" % \
- (file_result[-1]))
+ self.logger.debug(" Modlist/Ignore "
+ "match: %s" %
+ (file_result[-1]))
- if instance_fail == True:
- self.logger.debug("*** Instance %s failed RPM verification ***" % \
+ if instance_fail:
+ self.logger.debug("*** Instance %s failed RPM "
+ "verification ***" %
self.str_evra(inst))
- qtext_versions = qtext_versions + 'R(%s) ' % self.str_evra(inst)
+ qtext_versions = qtext_versions + \
+ 'R(%s) ' % self.str_evra(inst)
self.modlists[entry] = modlist
- # Attach status structure for return to server for reporting.
- inst.set('verify_status', str(self.instance_status[inst]))
+ # Attach status structure for reporting.
+ inst.set('verify_status',
+ str(self.instance_status[inst]))
- if self.instance_status[inst]['installed'] == False or \
- self.instance_status[inst].get('version_fail', False)== True or \
- self.instance_status[inst].get('verify_fail', False) == True:
+ version_fail = self.instance_status[inst].get(
+ 'version_fail', False)
+ verify_fail = self.instance_status[inst].get(
+ 'verify_fail', False)
+ if not self.instance_status[inst]['installed'] or \
+ version_fail or verify_fail:
package_fail = True
self.instance_status[inst]['pkg'] = entry
self.modlists[entry] = modlist
# Find Installed Instances that are not in the Config.
- extra_installed = self.FindExtraInstances(entry, self.installed[entry.get('name')])
- if extra_installed != None:
+ extra_installed = self.FindExtraInstances(
+ entry, self.installed[entry.get('name')])
+ if extra_installed is not None:
package_fail = True
self.extra_instances.append(extra_installed)
for inst in extra_installed.findall('Instance'):
- qtext_versions = qtext_versions + 'D(%s) ' % self.str_evra(inst)
- self.logger.debug("Found Extra Instances %s" % qtext_versions)
-
- if package_fail == True:
- self.logger.info(" Package %s failed verification." % \
- (entry.get('name')))
- qtext = 'Install/Upgrade/delete Package %s instance(s) - %s (y/N) ' % \
- (entry.get('name'), qtext_versions)
+ qtext_versions = qtext_versions + \
+ 'D(%s) ' % self.str_evra(inst)
+ self.logger.debug("Found Extra Instances %s" %
+ qtext_versions)
+
+ if package_fail:
+ self.logger.info(" Package %s failed verification."
+ % (entry.get('name')))
+ qtext = 'Install/Upgrade/delete Package %s instance(s) - '\
+ '%s (y/N) ' % (entry.get('name'), qtext_versions)
entry.set('qtext', qtext)
bcfg2_versions = ''
- for bcfg2_inst in [inst for inst in instances if inst.tag == 'Instance']:
- bcfg2_versions = bcfg2_versions + '(%s) ' % self.str_evra(bcfg2_inst)
+ for bcfg2_inst in [inst for inst in instances
+ if inst.tag == 'Instance']:
+ bcfg2_versions = bcfg2_versions + \
+ '(%s) ' % self.str_evra(bcfg2_inst)
if bcfg2_versions != '':
entry.set('version', bcfg2_versions)
installed_versions = ''
for installed_inst in self.installed[entry.get('name')]:
- installed_versions = installed_versions + '(%s) ' % \
- self.str_evra(installed_inst)
+ installed_versions = installed_versions + \
+ '(%s) ' % self.str_evra(installed_inst)
entry.set('current_version', installed_versions)
return False
else:
# There are no Instances of this package installed.
- self.logger.debug("Package %s has no instances installed" % (entry.get('name')))
+ self.logger.debug("Package %s has no instances installed" %
+ (entry.get('name')))
entry.set('current_exists', 'false')
bcfg2_versions = ''
for inst in instances:
- qtext_versions = qtext_versions + 'I(%s) ' % self.str_evra(inst)
+ qtext_versions = qtext_versions + \
+ 'I(%s) ' % self.str_evra(inst)
self.instance_status.setdefault(inst, {})['installed'] = False
self.modlists[entry] = modlist
self.instance_status[inst]['pkg'] = entry
if inst.tag == 'Instance':
- bcfg2_versions = bcfg2_versions + '(%s) ' % self.str_evra(inst)
+ bcfg2_versions = bcfg2_versions + \
+ '(%s) ' % self.str_evra(inst)
if bcfg2_versions != '':
entry.set('version', bcfg2_versions)
- entry.set('qtext', "Install Package %s Instance(s) %s? (y/N) " % \
+ entry.set('qtext', "Install Package %s Instance(s) %s? (y/N) " %
(entry.get('name'), qtext_versions))
return False
@@ -421,26 +1614,31 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
for pkg in packages:
for inst in pkg:
if pkg.get('name') != 'gpg-pubkey':
- pkgspec = { 'name':pkg.get('name'),
- 'epoch':inst.get('epoch', None),
- 'version':inst.get('version'),
- 'release':inst.get('release'),
- 'arch':inst.get('arch') }
+ pkgspec = {'name': pkg.get('name'),
+ 'epoch': inst.get('epoch', None),
+ 'version': inst.get('version'),
+ 'release': inst.get('release'),
+ 'arch': inst.get('arch')}
pkgspec_list.append(pkgspec)
else:
- pkgspec = { 'name':pkg.get('name'),
- 'version':inst.get('version'),
- 'release':inst.get('release')}
- self.logger.info("WARNING: gpg-pubkey package not in configuration %s %s"\
- % (pkgspec.get('name'), self.str_evra(pkgspec)))
- self.logger.info(" This package will be deleted in a future version of the RPM driver.")
+ pkgspec = {'name': pkg.get('name'),
+ 'version': inst.get('version'),
+ 'release': inst.get('release')}
+ self.logger.info("WARNING: gpg-pubkey package not in "
+ "configuration %s %s" %
+ (pkgspec.get('name'),
+ self.str_evra(pkgspec)))
+ self.logger.info(" This package will be deleted "
+ "in a future version of the RPM driver.")
#pkgspec_list.append(pkg_spec)
- erase_results = rpmtools.rpm_erase(pkgspec_list, self.erase_flags)
+ erase_results = rpm_erase(pkgspec_list,
+ Bcfg2.Options.setup.rpm_erase_flags)
if erase_results == []:
self.modified += packages
for pkg in pkgspec_list:
- self.logger.info("Deleted %s %s" % (pkg.get('name'), self.str_evra(pkg)))
+ self.logger.info("Deleted %s %s" % (pkg.get('name'),
+ self.str_evra(pkg)))
else:
self.logger.info("Bulk erase failed with errors:")
self.logger.debug("Erase results = %s" % erase_results)
@@ -450,30 +1648,38 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
pkg_modified = False
for inst in pkg:
if pkg.get('name') != 'gpg-pubkey':
- pkgspec = { 'name':pkg.get('name'),
- 'epoch':inst.get('epoch', None),
- 'version':inst.get('version'),
- 'release':inst.get('release'),
- 'arch':inst.get('arch') }
+ pkgspec = {'name': pkg.get('name'),
+ 'epoch': inst.get('epoch', None),
+ 'version': inst.get('version'),
+ 'release': inst.get('release'),
+ 'arch': inst.get('arch')}
pkgspec_list.append(pkgspec)
else:
- pkgspec = { 'name':pkg.get('name'),
- 'version':inst.get('version'),
- 'release':inst.get('release')}
- self.logger.info("WARNING: gpg-pubkey package not in configuration %s %s"\
- % (pkgspec.get('name'), self.str_evra(pkgspec)))
- self.logger.info(" This package will be deleted in a future version of the RPM driver.")
- continue # Don't delete the gpg-pubkey packages for now.
- erase_results = rpmtools.rpm_erase([pkgspec], self.erase_flags)
+ pkgspec = {'name': pkg.get('name'),
+ 'version': inst.get('version'),
+ 'release': inst.get('release')}
+ self.logger.info("WARNING: gpg-pubkey package not in "
+ "configuration %s %s" %
+ (pkgspec.get('name'),
+ self.str_evra(pkgspec)))
+ self.logger.info(" This package will be "
+ "deleted in a future version of the "
+ "RPM driver.")
+ continue # don't delete the gpg-pubkey packages
+ erase_results = rpm_erase(
+ [pkgspec],
+ Bcfg2.Options.setup.rpm_erase_flags)
if erase_results == []:
pkg_modified = True
- self.logger.info("Deleted %s %s" % \
- (pkgspec.get('name'), self.str_evra(pkgspec)))
+ self.logger.info("Deleted %s %s" %
+ (pkgspec.get('name'),
+ self.str_evra(pkgspec)))
else:
- self.logger.error("unable to delete %s %s" % \
- (pkgspec.get('name'), self.str_evra(pkgspec)))
+ self.logger.error("unable to delete %s %s" %
+ (pkgspec.get('name'),
+ self.str_evra(pkgspec)))
self.logger.debug("Failure = %s" % erase_results)
- if pkg_modified == True:
+ if pkg_modified:
self.modified.append(pkg)
self.RefreshPackages()
@@ -489,33 +1695,35 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
"""
fix = False
- if inst_status.get('installed', False) == False:
- if instance.get('installed_action', 'install') == "install" and \
- self.installed_action == "install":
+ if not inst_status.get('installed', False):
+ if (instance.get('install_missing', 'true').lower() == "true" and
+ Bcfg2.Options.setup.rpm_install_missing):
fix = True
else:
- self.logger.debug('Installed Action for %s %s is to not install' % \
+ self.logger.debug('Installed Action for %s %s is to not '
+ 'install' %
(inst_status.get('pkg').get('name'),
self.str_evra(instance)))
- elif inst_status.get('version_fail', False) == True:
- if instance.get('version_fail_action', 'upgrade') == "upgrade" and \
- self.version_fail_action == "upgrade":
+ elif inst_status.get('version_fail', False):
+ if (instance.get('fix_version', 'true').lower() == "true" and
+ Bcfg2.Options.setup.rpm_fix_version):
fix = True
else:
- self.logger.debug('Version Fail Action for %s %s is to not upgrade' % \
+ self.logger.debug('Version Fail Action for %s %s is to '
+ 'not upgrade' %
(inst_status.get('pkg').get('name'),
self.str_evra(instance)))
- elif inst_status.get('verify_fail', False) == True and self.name == "RPM":
- # yum can't reinstall packages so only do this for rpm.
- if instance.get('verify_fail_action', 'reinstall') == "reinstall" and \
- self.verify_fail_action == "reinstall":
+ elif inst_status.get('verify_fail', False):
+ if (instance.get('reinstall_broken', 'true').lower() == "true" and
+ Bcfg2.Options.setup.rpm_reinstall_broken):
for inst in inst_status.get('verify'):
# This needs to be a for loop rather than a straight get()
# because the underlying routines handle multiple packages
# and return a list of results.
- self.logger.debug('reinstall_check: %s %s:%s-%s.%s' % inst.get('nevra'))
+ self.logger.debug('reinstall_check: %s %s:%s-%s.%s' %
+ inst.get('nevra'))
if inst.get("hdr", False):
fix = True
@@ -523,7 +1731,8 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
elif inst.get('files', False):
# Parse rpm verify file results
for file_result in inst.get('files', []):
- self.logger.debug('reinstall_check: file: %s' % file_result)
+ self.logger.debug('reinstall_check: file: %s' %
+ file_result)
if file_result[-2] != 'c':
fix = True
break
@@ -532,13 +1741,14 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
elif inst.get("deps", False):
fix = False
else:
- self.logger.debug('Verify Fail Action for %s %s is to not reinstall' % \
- (inst_status.get('pkg').get('name'),
- self.str_evra(instance)))
+ self.logger.debug('Verify Fail Action for %s %s is to not '
+ 'reinstall' %
+ (inst_status.get('pkg').get('name'),
+ self.str_evra(instance)))
return fix
- def Install(self, packages, states):
+ def Install(self, packages):
"""
Try and fix everything that RPM.VerifyPackages() found wrong for
each Package Entry. This can result in individual RPMs being
@@ -559,6 +1769,7 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
"""
self.logger.info('Runing RPM.Install()')
+ states = dict()
install_only_pkgs = []
gpg_keys = []
upgrade_pkgs = []
@@ -566,20 +1777,21 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
# Remove extra instances.
# Can not reverify because we don't have a package entry.
if len(self.extra_instances) > 0:
- if (self.setup.get('remove') == 'all' or \
- self.setup.get('remove') == 'packages') and\
- not self.setup.get('dryrun'):
+ if (Bcfg2.Options.setup.remove in ['all', 'packages'] and
+ not Bcfg2.Options.setup.dry_run):
self.Remove(self.extra_instances)
else:
- self.logger.info("The following extra package instances will be removed by the '-r' option:")
+ self.logger.info("The following extra package instances will "
+ "be removed by the '-r' option:")
for pkg in self.extra_instances:
for inst in pkg:
- self.logger.info(" %s %s" % (pkg.get('name'), self.str_evra(inst)))
+ self.logger.info(" %s %s" % (pkg.get('name'),
+ self.str_evra(inst)))
# Figure out which instances of the packages actually need something
# doing to them and place in the appropriate work 'queue'.
for pkg in packages:
- for inst in [instn for instn in pkg if instn.tag \
+ for inst in [instn for instn in pkg if instn.tag
in ['Instance', 'Package']]:
if self.FixInstance(inst, self.instance_status[inst]):
if pkg.get('name') == 'gpg-pubkey':
@@ -592,10 +1804,10 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
# Fix installOnlyPackages
if len(install_only_pkgs) > 0:
self.logger.info("Attempting to install 'install only packages'")
- install_args = \
- " ".join(os.path.join(self.instance_status[inst].get('pkg').get('uri'),
- inst.get('simplefile'))
- for inst in install_only_pkgs)
+ install_args = " ".join(os.path.join(
+ self.instance_status[inst].get('pkg').get('uri'),
+ inst.get('simplefile'))
+ for inst in install_only_pkgs)
if self.cmd.run("rpm --install --quiet --oldpackage --replacepkgs "
"%s" % install_args):
# The rpm command succeeded. All packages installed.
@@ -607,35 +1819,34 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
self.logger.error("Single Pass for InstallOnlyPackages Failed")
installed_instances = []
for inst in install_only_pkgs:
- install_args = \
- os.path.join(self.instance_status[inst].get('pkg').get('uri'),
- inst.get('simplefile'))
+ pkguri = self.instance_status[inst].get('pkg').get('uri')
+ pkgname = self.instance_status[inst].get('pkg').get('name')
+ install_args = os.path.join(pkguri, inst.get('simplefile'))
if self.cmd.run("rpm --install --quiet --oldpackage "
"--replacepkgs %s" % install_args):
installed_instances.append(inst)
else:
- self.logger.debug("InstallOnlyPackage %s %s would not install." % \
- (self.instance_status[inst].get('pkg').get('name'), \
- self.str_evra(inst)))
+ self.logger.debug("InstallOnlyPackage %s %s would not "
+ "install." % (pkgname,
+ self.str_evra(inst)))
- install_pkg_set = set([self.instance_status[inst].get('pkg') \
- for inst in install_only_pkgs])
+ install_pkg_set = set([self.instance_status[inst].get('pkg')
+ for inst in install_only_pkgs])
self.RefreshPackages()
# Install GPG keys.
if len(gpg_keys) > 0:
for inst in gpg_keys:
self.logger.info("Installing GPG keys.")
- key_arg = os.path.join(self.instance_status[inst].get('pkg').get('uri'), \
- inst.get('simplefile'))
+ pkguri = self.instance_status[inst].get('pkg').get('uri')
+ pkgname = self.instance_status[inst].get('pkg').get('name')
+ key_arg = os.path.join(pkguri, inst.get('simplefile'))
if not self.cmd.run("rpm --import %s" % key_arg):
self.logger.debug("Unable to install %s-%s" %
- (self.instance_status[inst].get('pkg').get('name'),
- self.str_evra(inst)))
+ (pkgname, self.str_evra(inst)))
else:
self.logger.debug("Installed %s-%s-%s" %
- (self.instance_status[inst].get('pkg').get('name'),
- inst.get('version'),
+ (pkgname, inst.get('version'),
inst.get('release')))
self.RefreshPackages()
self.gpg_keyids = self.getinstalledgpg()
@@ -645,9 +1856,10 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
# Fix upgradeable packages.
if len(upgrade_pkgs) > 0:
self.logger.info("Attempting to upgrade packages")
- upgrade_args = " ".join([os.path.join(self.instance_status[inst].get('pkg').get('uri'), \
- inst.get('simplefile')) \
- for inst in upgrade_pkgs])
+ upgrade_args = " ".join([os.path.join(
+ self.instance_status[inst].get('pkg').get('uri'),
+ inst.get('simplefile'))
+ for inst in upgrade_pkgs])
if self.cmd.run("rpm --upgrade --quiet --oldpackage --replacepkgs "
"%s" % upgrade_args):
# The rpm command succeeded. All packages upgraded.
@@ -661,30 +1873,38 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
self.logger.error("Single Pass for Upgrading Packages Failed")
upgraded_instances = []
for inst in upgrade_pkgs:
- upgrade_args = os.path.join(self.instance_status[inst].get('pkg').get('uri'), \
- inst.get('simplefile'))
- #self.logger.debug("rpm --upgrade --quiet --oldpackage --replacepkgs %s" % \
- # upgrade_args)
+ upgrade_args = os.path.join(
+ self.instance_status[inst].get('pkg').get('uri'),
+ inst.get('simplefile'))
+ #self.logger.debug("rpm --upgrade --quiet --oldpackage "
+ # "--replacepkgs %s" % upgrade_args)
if self.cmd.run("rpm --upgrade --quiet --oldpackage "
"--replacepkgs %s" % upgrade_args):
upgraded_instances.append(inst)
else:
- self.logger.debug("Package %s %s would not upgrade." %
- (self.instance_status[inst].get('pkg').get('name'),
- self.str_evra(inst)))
+ self.logger.debug(
+ "Package %s %s would not upgrade." %
+ (self.instance_status[inst].get('pkg').get('name'),
+ self.str_evra(inst)))
- upgrade_pkg_set = set([self.instance_status[inst].get('pkg') \
- for inst in upgrade_pkgs])
+ upgrade_pkg_set = set([self.instance_status[inst].get('pkg')
+ for inst in upgrade_pkgs])
self.RefreshPackages()
- if not self.setup['kevlar']:
+ if not Bcfg2.Options.setup.kevlar:
for pkg_entry in packages:
- self.logger.debug("Reverifying Failed Package %s" % (pkg_entry.get('name')))
- states[pkg_entry] = self.VerifyPackage(pkg_entry, \
- self.modlists.get(pkg_entry, []))
+ self.logger.debug("Reverifying Failed Package %s" %
+ (pkg_entry.get('name')))
+ states[pkg_entry] = self.VerifyPackage(
+ pkg_entry, self.modlists.get(pkg_entry, []))
- for entry in [ent for ent in packages if states[ent]]:
- self.modified.append(entry)
+ self.modified.extend(ent for ent in packages if states[ent])
+ return states
+
+ def _log_incomplete_entry_install(self, etag, ename):
+ self.logger.error("Incomplete information for entry %s:%s; "
+ "cannot install" % (etag, ename))
+ return
def canInstall(self, entry):
"""Test if entry has enough information to be installed."""
@@ -692,18 +1912,17 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
return False
if 'failure' in entry.attrib:
- self.logger.error("Cannot install entry %s:%s with bind failure" % \
+ self.logger.error("Cannot install entry %s:%s with bind failure" %
(entry.tag, entry.get('name')))
return False
-
instances = entry.findall('Instance')
- # If the entry wasn't verifiable, then we really don't want to try and fix something
- # that we don't know is broken.
+ # If the entry wasn't verifiable, then we really don't want to try
+ # and fix something that we don't know is broken.
if not self.canVerify(entry):
- self.logger.debug("WARNING: Package %s was not verifiable, not passing to Install()" \
- % entry.get('name'))
+ self.logger.debug("WARNING: Package %s was not verifiable, not "
+ "passing to Install()" % entry.get('name'))
return False
if not instances:
@@ -711,53 +1930,70 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
if entry.get('name') == 'gpg-pubkey':
# gpg-pubkey packages aren't really pacakges, so we have to do
# something a little different.
- # Check that the Package Level has what we need for verification.
- if [attr for attr in self.__gpg_ireq__[entry.tag] if attr not in entry.attrib]:
- self.logger.error("Incomplete information for entry %s:%s; cannot install" \
- % (entry.tag, entry.get('name')))
+ # check that the Package level has
+ # what we need for verification.
+ if [attr for attr in self.__gpg_ireq__[entry.tag]
+ if attr not in entry.attrib]:
+ self._log_incomplete_entry_install(entry.tag,
+ entry.get('name'))
return False
else:
- if [attr for attr in self.__ireq__[entry.tag] if attr not in entry.attrib]:
- self.logger.error("Incomplete information for entry %s:%s; cannot install" \
- % (entry.tag, entry.get('name')))
+ if [attr for attr in self.__ireq__[entry.tag]
+ if attr not in entry.attrib]:
+ self._log_incomplete_entry_install(entry.tag,
+ entry.get('name'))
return False
else:
if entry.get('name') == 'gpg-pubkey':
# gpg-pubkey packages aren't really pacakges, so we have to do
# something a little different.
- # Check that the Package Level has what we need for verification.
- if [attr for attr in self.__new_gpg_ireq__[entry.tag] if attr not in entry.attrib]:
- self.logger.error("Incomplete information for entry %s:%s; cannot install" \
- % (entry.tag, entry.get('name')))
+ # check that the Package level has
+ # what we need for verification.
+ if [attr for attr in self.__new_gpg_ireq__[entry.tag]
+ if attr not in entry.attrib]:
+ self._log_incomplete_entry_install(entry.tag,
+ entry.get('name'))
return False
- # Check that the Instance Level has what we need for verification.
+ # check that the Instance level has
+ # what we need for verification.
for inst in instances:
- if [attr for attr in self.__new_gpg_ireq__[inst.tag] \
- if attr not in inst.attrib]:
- self.logger.error("Incomplete information for entry %s:%s; cannot install"\
- % (inst.tag, entry.get('name')))
+ if [attr for attr in self.__new_gpg_ireq__[inst.tag]
+ if attr not in inst.attrib]:
+ self._log_incomplete_entry_install(inst.tag,
+ entry.get('name'))
return False
else:
# New format with Instances.
- # Check that the Package Level has what we need for verification.
- if [attr for attr in self.__new_ireq__[entry.tag] if attr not in entry.attrib]:
- self.logger.error("Incomplete information for entry %s:%s; cannot install" \
- % (entry.tag, entry.get('name')))
- self.logger.error(" Required attributes that may not be present are %s" \
- % (self.__new_ireq__[entry.tag]))
+ # check that the Package level has
+ # what we need for verification.
+ if [attr for attr in self.__new_ireq__[entry.tag]
+ if attr not in entry.attrib]:
+ self._log_incomplete_entry_install(entry.tag,
+ entry.get('name'))
+ self.logger.error(" Required attributes that "
+ "may not be present are %s" %
+ (self.__new_ireq__[entry.tag]))
return False
- # Check that the Instance Level has what we need for verification.
+ # check that the Instance level has
+ # what we need for verification.
for inst in instances:
if inst.tag == 'Instance':
- if [attr for attr in self.__new_ireq__[inst.tag] \
- if attr not in inst.attrib]:
- self.logger.error("Incomplete information for %s of package %s; cannot install" \
- % (inst.tag, entry.get('name')))
- self.logger.error(" Required attributes that may not be present are %s" \
+ if [attr for attr in self.__new_ireq__[inst.tag]
+ if attr not in inst.attrib]:
+ self._log_incomplete_entry_install(
+ inst.tag,
+ entry.get('name'))
+ self.logger.error(" Required attributes "
+ "that may not be present are %s"
% (self.__new_ireq__[inst.tag]))
return False
return True
+ def _log_incomplete_entry_verify(self, etag, ename):
+ self.logger.error("Incomplete information for entry %s:%s; "
+ "cannot verify" % (etag, ename))
+ return
+
def canVerify(self, entry):
"""
Test if entry has enough information to be verified.
@@ -775,13 +2011,15 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
return False
if 'failure' in entry.attrib:
- self.logger.error("Entry %s:%s reports bind failure: %s" % \
- (entry.tag, entry.get('name'), entry.get('failure')))
+ self.logger.error("Entry %s:%s reports bind failure: %s" %
+ (entry.tag, entry.get('name'),
+ entry.get('failure')))
return False
- # We don't want to do any checks so we don't care what the entry has in it.
- if (not self.pkg_checks or
- entry.get('pkg_checks', 'true').lower() == 'false'):
+ # we don't want to do any checks so
+ # we don't care what the entry has in it.
+ if (not Bcfg2.Options.setup.rpm_pkg_checks or
+ entry.get('pkg_checks', 'true').lower() == 'false'):
return True
instances = entry.findall('Instance')
@@ -791,53 +2029,72 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
if entry.get('name') == 'gpg-pubkey':
# gpg-pubkey packages aren't really pacakges, so we have to do
# something a little different.
- # Check that the Package Level has what we need for verification.
- if [attr for attr in self.__gpg_req__[entry.tag] if attr not in entry.attrib]:
- self.logger.error("Incomplete information for entry %s:%s; cannot verify" \
- % (entry.tag, entry.get('name')))
+ # check that the Package level has
+ # what we need for verification.
+ if [attr for attr in self.__gpg_req__[entry.tag]
+ if attr not in entry.attrib]:
+ self._log_incomplete_entry_verify(entry.tag,
+ entry.get('name'))
return False
elif entry.tag == 'Path' and entry.get('type') == 'ignore':
# ignored Paths are only relevant during failed package
# verification
pass
else:
- if [attr for attr in self.__req__[entry.tag] if attr not in entry.attrib]:
- self.logger.error("Incomplete information for entry %s:%s; cannot verify" \
- % (entry.tag, entry.get('name')))
+ if [attr for attr in self.__req__[entry.tag]
+ if attr not in entry.attrib]:
+ self._log_incomplete_entry_verify(entry.tag,
+ entry.get('name'))
return False
else:
if entry.get('name') == 'gpg-pubkey':
# gpg-pubkey packages aren't really pacakges, so we have to do
# something a little different.
- # Check that the Package Level has what we need for verification.
- if [attr for attr in self.__new_gpg_req__[entry.tag] if attr not in entry.attrib]:
- self.logger.error("Incomplete information for entry %s:%s; cannot verify" \
- % (entry.tag, entry.get('name')))
+ # check that the Package level has
+ # what we need for verification.
+ if [attr for attr in self.__new_gpg_req__[entry.tag]
+ if attr not in entry.attrib]:
+ self._log_incomplete_entry_verify(entry.tag,
+ entry.get('name'))
return False
- # Check that the Instance Level has what we need for verification.
+ # check that the Instance level has
+ # what we need for verification.
for inst in instances:
- if [attr for attr in self.__new_gpg_req__[inst.tag] \
- if attr not in inst.attrib]:
- self.logger.error("Incomplete information for entry %s:%s; cannot verify" \
- % (inst.tag, inst.get('name')))
+ if [attr for attr in self.__new_gpg_req__[inst.tag]
+ if attr not in inst.attrib]:
+ self._log_incomplete_entry_verify(inst.tag,
+ inst.get('name'))
return False
else:
- # New format with Instances, or old style modified.
- # Check that the Package Level has what we need for verification.
- if [attr for attr in self.__new_req__[entry.tag] if attr not in entry.attrib]:
- self.logger.error("Incomplete information for entry %s:%s; cannot verify" \
- % (entry.tag, entry.get('name')))
+ # new format with Instances, or old style modified.
+ # check that the Package level has
+ # what we need for verification.
+ if [attr for attr in self.__new_req__[entry.tag]
+ if attr not in entry.attrib]:
+ self._log_incomplete_entry_verify(entry.tag,
+ entry.get('name'))
return False
- # Check that the Instance Level has what we need for verification.
+ # check that the Instance level has
+ # what we need for verification.
for inst in instances:
if inst.tag == 'Instance':
- if [attr for attr in self.__new_req__[inst.tag] \
- if attr not in inst.attrib]:
- self.logger.error("Incomplete information for entry %s:%s; cannot verify" \
- % (inst.tag, inst.get('name')))
+ if [attr for attr in self.__new_req__[inst.tag]
+ if attr not in inst.attrib]:
+ self._log_incomplete_entry_verify(inst.tag,
+ inst.get('name'))
return False
return True
+ def _get_tmp_entry(self, extra_entry, inst):
+ tmp_entry = Bcfg2.Client.XML.SubElement(extra_entry, 'Instance',
+ version=inst.get('version'),
+ release=inst.get('release'))
+ if inst.get('epoch', None) is not None:
+ tmp_entry.set('epoch', str(inst.get('epoch')))
+ if installed_inst.get('arch', None) is not None:
+ tmp_entry.set('arch', inst.get('arch'))
+ return
+
def FindExtra(self):
"""Find extra packages."""
packages = [entry.get('name') for entry in self.getSupportedEntries()]
@@ -845,22 +2102,17 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
for (name, instances) in list(self.installed.items()):
if name not in packages:
- extra_entry = Bcfg2.Client.XML.Element('Package', name=name, type=self.pkgtype)
+ extra_entry = Bcfg2.Client.XML.Element('Package',
+ name=name,
+ type=self.pkgtype)
for installed_inst in instances:
- if self.setup['extra']:
- self.logger.info("Extra Package %s %s." % \
+ if Bcfg2.Options.setup.extra:
+ self.logger.info("Extra Package %s %s." %
(name, self.str_evra(installed_inst)))
- tmp_entry = Bcfg2.Client.XML.SubElement(extra_entry, 'Instance', \
- version = installed_inst.get('version'), \
- release = installed_inst.get('release'))
- if installed_inst.get('epoch', None) != None:
- tmp_entry.set('epoch', str(installed_inst.get('epoch')))
- if installed_inst.get('arch', None) != None:
- tmp_entry.set('arch', installed_inst.get('arch'))
+ self._get_tmp_entry(extra_entry, installed_inst)
extras.append(extra_entry)
return extras
-
def FindExtraInstances(self, pkg_entry, installed_entry):
"""
Check for installed instances that are not in the config.
@@ -869,8 +2121,11 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
"""
name = pkg_entry.get('name')
- extra_entry = Bcfg2.Client.XML.Element('Package', name=name, type=self.pkgtype)
- instances = [inst for inst in pkg_entry if inst.tag == 'Instance' or inst.tag == 'Package']
+ extra_entry = Bcfg2.Client.XML.Element('Package',
+ name=name,
+ type=self.pkgtype)
+ instances = [inst for inst in pkg_entry if
+ inst.tag == 'Instance' or inst.tag == 'Package']
if name in self.installOnlyPkgs:
for installed_inst in installed_entry:
not_found = True
@@ -879,36 +2134,25 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
self.inst_evra_equal(inst, installed_inst):
not_found = False
break
- if not_found == True:
+ if not_found:
# Extra package.
- self.logger.info("Extra InstallOnlyPackage %s %s." % \
+ self.logger.info("Extra InstallOnlyPackage %s %s." %
(name, self.str_evra(installed_inst)))
- tmp_entry = Bcfg2.Client.XML.SubElement(extra_entry, 'Instance', \
- version = installed_inst.get('version'), \
- release = installed_inst.get('release'))
- if installed_inst.get('epoch', None) != None:
- tmp_entry.set('epoch', str(installed_inst.get('epoch')))
- if installed_inst.get('arch', None) != None:
- tmp_entry.set('arch', installed_inst.get('arch'))
+ self._get_tmp_entry(extra_entry, installed_inst)
else:
# Normal package, only check arch.
for installed_inst in installed_entry:
not_found = True
for inst in instances:
- if installed_inst.get('arch', None) == inst.get('arch', None) or\
- inst.tag == 'Package':
+ if (installed_inst.get('arch', None) ==
+ inst.get('arch', None) or
+ inst.tag == 'Package'):
not_found = False
break
if not_found:
- self.logger.info("Extra Normal Package Instance %s %s" % \
+ self.logger.info("Extra Normal Package Instance %s %s" %
(name, self.str_evra(installed_inst)))
- tmp_entry = Bcfg2.Client.XML.SubElement(extra_entry, 'Instance', \
- version = installed_inst.get('version'), \
- release = installed_inst.get('release'))
- if installed_inst.get('epoch', None) != None:
- tmp_entry.set('epoch', str(installed_inst.get('epoch')))
- if installed_inst.get('arch', None) != None:
- tmp_entry.set('arch', installed_inst.get('arch'))
+ self._get_tmp_entry(extra_entry, installed_inst)
if len(extra_entry) == 0:
extra_entry = None
@@ -932,9 +2176,10 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
Compare old style entry to installed entry. Which means ignore
the epoch and arch.
'''
- if (config_entry.tag == 'Package' and \
- config_entry.get('version') == installed_entry.get('version') and \
- config_entry.get('release') == installed_entry.get('release')):
+ if (config_entry.tag == 'Package' and
+ config_entry.get('version') == installed_entry.get('version')
+ and
+ config_entry.get('release') == installed_entry.get('release')):
return True
else:
return False
@@ -942,18 +2187,19 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
def inst_evra_equal(self, config_entry, installed_entry):
"""Compare new style instance to installed entry."""
- if config_entry.get('epoch', None) != None:
+ if config_entry.get('epoch', None) is not None:
epoch = int(config_entry.get('epoch'))
else:
epoch = None
- if (config_entry.tag == 'Instance' and \
- (epoch == installed_entry.get('epoch', 0) or \
- (epoch == 0 and installed_entry.get('epoch', 0) == None) or \
- (epoch == None and installed_entry.get('epoch', 0) == 0)) and \
- config_entry.get('version') == installed_entry.get('version') and \
- config_entry.get('release') == installed_entry.get('release') and \
- config_entry.get('arch', None) == installed_entry.get('arch', None)):
+ if (config_entry.tag == 'Instance' and
+ (epoch == installed_entry.get('epoch', 0) or
+ (epoch == 0 and installed_entry.get('epoch', 0) is None) or
+ (epoch is None and installed_entry.get('epoch', 0) == 0)) and
+ config_entry.get('version') == installed_entry.get('version') and
+ config_entry.get('release') == installed_entry.get('release') and
+ config_entry.get('arch', None) == installed_entry.get('arch',
+ None)):
return True
else:
return False
@@ -966,10 +2212,10 @@ class RPM(Bcfg2.Client.Tools.PkgTool):
(big-endian) of the key ID which is good enough for our purposes.
"""
- init_ts = rpmtools.rpmtransactionset()
- init_ts.setVSFlags(rpm._RPMVSF_NODIGESTS|rpm._RPMVSF_NOSIGNATURES)
- gpg_hdrs = rpmtools.getheadersbykeyword(init_ts, **{'name':'gpg-pubkey'})
- keyids = [ header[rpm.RPMTAG_VERSION] for header in gpg_hdrs]
+ init_ts = rpmtransactionset()
+ init_ts.setVSFlags(rpm._RPMVSF_NODIGESTS | rpm._RPMVSF_NOSIGNATURES)
+ gpg_hdrs = getheadersbykeyword(init_ts, **{'name': 'gpg-pubkey'})
+ keyids = [header[rpm.RPMTAG_VERSION] for header in gpg_hdrs]
keyids.append('None')
init_ts.closeDB()
del init_ts
diff --git a/src/lib/Bcfg2/Client/Tools/RPMng.py b/src/lib/Bcfg2/Client/Tools/RPMng.py
deleted file mode 100644
index 0f0e4c700..000000000
--- a/src/lib/Bcfg2/Client/Tools/RPMng.py
+++ /dev/null
@@ -1,9 +0,0 @@
-""" RPM driver called 'RPMng' for backwards compat """
-
-from Bcfg2.Client.Tools.RPM import RPM
-
-
-class RPMng(RPM):
- """ RPM driver called 'RPMng' for backwards compat """
- deprecated = True
- name = "RPM"
diff --git a/src/lib/Bcfg2/Client/Tools/RcUpdate.py b/src/lib/Bcfg2/Client/Tools/RcUpdate.py
index e0c913dcd..a482dbc00 100644
--- a/src/lib/Bcfg2/Client/Tools/RcUpdate.py
+++ b/src/lib/Bcfg2/Client/Tools/RcUpdate.py
@@ -98,10 +98,10 @@ class RcUpdate(Bcfg2.Client.Tools.SvcTool):
# make sure service is disabled on boot
bootcmd = '/sbin/rc-update del %s default'
bootcmdrv = self.cmd.run(bootcmd % entry.get('name')).success
- if self.setup['servicemode'] == 'disabled':
+ if Bcfg2.Options.setup.service_mode == 'disabled':
# 'disabled' means we don't attempt to modify running svcs
return bootcmdrv
- buildmode = self.setup['servicemode'] == 'build'
+ buildmode = Bcfg2.Options.setup.service_mode == 'build'
if (entry.get('status') == 'on' and not buildmode) and \
entry.get('current_status') == 'off':
svccmdrv = self.start_service(entry)
diff --git a/src/lib/Bcfg2/Client/Tools/SELinux.py b/src/lib/Bcfg2/Client/Tools/SELinux.py
index 0b4aba60d..7b5ff7813 100644
--- a/src/lib/Bcfg2/Client/Tools/SELinux.py
+++ b/src/lib/Bcfg2/Client/Tools/SELinux.py
@@ -7,6 +7,7 @@ import copy
import glob
import struct
import socket
+import logging
import selinux
import seobject
import Bcfg2.Client.XML
@@ -77,14 +78,13 @@ class SELinux(Bcfg2.Client.Tools.Tool):
SEPort=['name', 'selinuxtype'],
SEUser=['name', 'roles', 'prefix'])
- def __init__(self, logger, setup, config):
- Bcfg2.Client.Tools.Tool.__init__(self, logger, setup, config)
+ def __init__(self, config):
+ Bcfg2.Client.Tools.Tool.__init__(self, config)
self.handlers = {}
for handler in self.__handles__:
etype = handler[0]
self.handlers[etype] = \
- globals()["SELinux%sHandler" % etype.title()](self, logger,
- setup, config)
+ globals()["SELinux%sHandler" % etype.title()](self, config)
self.txn = False
self.post_txn_queue = []
@@ -100,10 +100,6 @@ class SELinux(Bcfg2.Client.Tools.Tool):
# http://docs.python.org/2/reference/datamodel.html#object.__getattr__
# for details
- def BundleUpdated(self, _, states):
- for handler in self.handlers.values():
- handler.BundleUpdated(states)
-
def FindExtra(self):
extra = []
for handler in self.handlers.values():
@@ -119,7 +115,7 @@ class SELinux(Bcfg2.Client.Tools.Tool):
in the specification """
return self.handlers[entry.tag].primarykey(entry)
- def Install(self, entries, states):
+ def Install(self, entries):
# start a transaction
semanage = seobject.semanageRecords("")
if hasattr(semanage, "start"):
@@ -129,13 +125,14 @@ class SELinux(Bcfg2.Client.Tools.Tool):
else:
self.logger.debug("SELinux transactions not supported; this may "
"slow things down considerably")
- Bcfg2.Client.Tools.Tool.Install(self, entries, states)
+ states = Bcfg2.Client.Tools.Tool.Install(self, entries)
if hasattr(semanage, "finish"):
self.logger.debug("Committing SELinux transaction")
semanage.finish()
self.txn = False
for func, arg, kwargs in self.post_txn_queue:
states[arg] = func(*arg, **kwargs)
+ return states
def GenericSEInstall(self, entry):
"""Dispatch install to the proper method according to entry tag"""
@@ -144,7 +141,7 @@ class SELinux(Bcfg2.Client.Tools.Tool):
def GenericSEVerify(self, entry, _):
"""Dispatch verify to the proper method according to entry tag"""
rv = self.handlers[entry.tag].Verify(entry)
- if entry.get('qtext') and self.setup['interactive']:
+ if entry.get('qtext') and Bcfg2.Options.setup.interactive:
entry.set('qtext',
'%s\nInstall %s: (y/N) ' %
(entry.get('qtext'),
@@ -174,10 +171,9 @@ class SELinuxEntryHandler(object):
custom_re = re.compile(r' (?P<name>\S+)$')
custom_format = None
- def __init__(self, tool, logger, setup, config):
+ def __init__(self, tool, config):
self.tool = tool
- self.logger = logger
- self.setup = setup
+ self.logger = logging.getLogger(self.__class__.__name__)
self.config = config
self._records = None
self._all = None
@@ -229,7 +225,7 @@ class SELinuxEntryHandler(object):
match = self.custom_re.search(cmd)
if match:
if (len(self.custom_format) == 1 and
- self.custom_format[0] == "name"):
+ self.custom_format[0] == "name"):
keys.append(match.group("name"))
else:
keys.append(tuple([match.group(k)
@@ -379,11 +375,6 @@ class SELinuxEntryHandler(object):
for key in records.keys()
if key not in specified]
- def BundleUpdated(self, states):
- """ perform any additional magic tasks that need to be run
- when a bundle is updated """
- pass
-
class SELinuxSebooleanHandler(SELinuxEntryHandler):
""" handle SELinux boolean entries """
@@ -631,8 +622,8 @@ class SELinuxSeuserHandler(SELinuxEntryHandler):
etype = "user"
value_format = ("prefix", None, None, "roles")
- def __init__(self, tool, logger, setup, config):
- SELinuxEntryHandler.__init__(self, tool, logger, setup, config)
+ def __init__(self, tool, config):
+ SELinuxEntryHandler.__init__(self, tool, config)
self.needs_prefix = False
@property
@@ -725,9 +716,9 @@ class SELinuxSemoduleHandler(SELinuxEntryHandler):
etype = "module"
value_format = (None, "disabled")
- def __init__(self, tool, logger, setup, config):
- SELinuxEntryHandler.__init__(self, tool, logger, setup, config)
- self.filetool = POSIXFile(logger, setup, config)
+ def __init__(self, tool, config):
+ SELinuxEntryHandler.__init__(self, tool, config)
+ self.filetool = POSIXFile(config)
try:
self.setype = selinux.selinux_getpolicytype()[1]
except IndexError:
diff --git a/src/lib/Bcfg2/Client/Tools/SYSV.py b/src/lib/Bcfg2/Client/Tools/SYSV.py
index 27c3d3785..332638de4 100644
--- a/src/lib/Bcfg2/Client/Tools/SYSV.py
+++ b/src/lib/Bcfg2/Client/Tools/SYSV.py
@@ -34,8 +34,8 @@ class SYSV(Bcfg2.Client.Tools.PkgTool):
pkgtype = 'sysv'
pkgtool = ("/usr/sbin/pkgadd %s -n -d %%s", (('%s %s', ['url', 'name'])))
- def __init__(self, logger, setup, config):
- Bcfg2.Client.Tools.PkgTool.__init__(self, logger, setup, config)
+ def __init__(self, config):
+ Bcfg2.Client.Tools.PkgTool.__init__(self, config)
# noaskfile needs to live beyond __init__ otherwise file is removed
self.noaskfile = tempfile.NamedTemporaryFile()
self.noaskname = self.noaskfile.name
@@ -81,9 +81,9 @@ class SYSV(Bcfg2.Client.Tools.PkgTool):
self.logger.debug("Calling install command: %s" % pkgcmd)
return pkgcmd
- def Install(self, packages, states):
+ def Install(self, packages):
self.pkgmogrify(packages)
- super(SYSV, self).Install(packages, states)
+ super(SYSV, self).Install(packages)
def RefreshPackages(self):
"""Refresh memory hashes of packages."""
@@ -119,7 +119,7 @@ class SYSV(Bcfg2.Client.Tools.PkgTool):
self.logger.debug("Package %s not installed" %
entry.get("name"))
else:
- if self.setup['quick'] or \
+ if Bcfg2.Options.setup.quick or \
entry.attrib.get('verify', 'true') == 'false':
return True
rv = self.cmd.run("/usr/sbin/pkgchk -n %s" % entry.get('name'))
diff --git a/src/lib/Bcfg2/Client/Tools/Systemd.py b/src/lib/Bcfg2/Client/Tools/Systemd.py
index 027d91c71..f7e5b1b0b 100644
--- a/src/lib/Bcfg2/Client/Tools/Systemd.py
+++ b/src/lib/Bcfg2/Client/Tools/Systemd.py
@@ -13,34 +13,81 @@ class Systemd(Bcfg2.Client.Tools.SvcTool):
__handles__ = [('Service', 'systemd')]
__req__ = {'Service': ['name', 'status']}
+ def get_svc_name(self, service):
+ """Append .service to name if name doesn't specify a unit type."""
+ svc = service.get('name')
+ if svc.endswith(('.service', '.socket', '.device', '.mount',
+ '.automount', '.swap', '.target', '.path',
+ '.timer', '.snapshot', '.slice', '.scope')):
+ return svc
+ else:
+ return '%s.service' % svc
+
def get_svc_command(self, service, action):
- return "/bin/systemctl %s %s.service" % (action, service.get('name'))
+ return "/bin/systemctl %s %s" % (action, self.get_svc_name(service))
def VerifyService(self, entry, _):
"""Verify Service status for entry."""
- if entry.get('status') == 'ignore':
+ entry.set('target_status', entry.get('status')) # for reporting
+
+ bootstatus = self.get_bootstatus(entry)
+ if bootstatus is None:
+ # bootstatus is unspecified and status is ignore
return True
- cmd = "/bin/systemctl status %s.service " % (entry.get('name'))
- rv = self.cmd.run(cmd)
+ if self.cmd.run(self.get_svc_command(entry, 'is-enabled')):
+ current_bootstatus = 'on'
+ else:
+ current_bootstatus = 'off'
- if 'Loaded: error' in rv.stdout:
- entry.set('current_status', 'off')
- return False
- elif 'Active: active' in rv.stdout:
- entry.set('current_status', 'on')
- return entry.get('status') == 'on'
+ if entry.get('status') == 'ignore':
+ return current_bootstatus == bootstatus
+
+ cmd = self.get_svc_command(entry, 'show') + ' -p ActiveState'
+ rv = self.cmd.run(cmd)
+ if rv.stdout.strip() in ('ActiveState=active',
+ 'ActiveState=activating',
+ 'ActiveState=reloading'):
+ current_status = 'on'
else:
- entry.set('current_status', 'off')
- return entry.get('status') == 'off'
+ current_status = 'off'
+ entry.set('current_status', current_status)
+ return (entry.get('status') == current_status and
+ bootstatus == current_bootstatus)
def InstallService(self, entry):
"""Install Service entry."""
- if entry.get('status') == 'on':
- rv = self.cmd.run(self.get_svc_command(entry, 'enable')).success
- rv &= self.cmd.run(self.get_svc_command(entry, 'start')).success
+ self.logger.info("Installing Service %s" % (entry.get('name')))
+ bootstatus = self.get_bootstatus(entry)
+ if bootstatus is None:
+ # bootstatus is unspecified and status is ignore
+ return True
+
+ # Enable or disable the service
+ if bootstatus == 'on':
+ cmd = self.get_svc_command(entry, 'enable')
+ else:
+ cmd = self.get_svc_command(entry, 'disable')
+ if not self.cmd.run(cmd).success:
+ # Return failure immediately and do not start/stop the service.
+ return False
+
+ # Start or stop the service, depending on the current servicemode
+ cmd = None
+ if Bcfg2.Options.setup.servicemode == 'disabled':
+ # 'disabled' means we don't attempt to modify running svcs
+ pass
+ elif Bcfg2.Options.setup.servicemode == 'build':
+ # 'build' means we attempt to stop all services started
+ if entry.get('current_status') == 'on':
+ cmd = self.get_svc_command(entry, 'stop')
else:
- rv = self.cmd.run(self.get_svc_command(entry, 'stop')).success
- rv &= self.cmd.run(self.get_svc_command(entry, 'disable')).success
+ if entry.get('status') == 'on':
+ cmd = self.get_svc_command(entry, 'start')
+ else:
+ cmd = self.get_svc_command(entry, 'stop')
- return rv
+ if cmd:
+ return self.cmd.run(cmd).success
+ else:
+ return True
diff --git a/src/lib/Bcfg2/Client/Tools/VCS.py b/src/lib/Bcfg2/Client/Tools/VCS.py
index 4fa2fb5e2..449503b55 100644
--- a/src/lib/Bcfg2/Client/Tools/VCS.py
+++ b/src/lib/Bcfg2/Client/Tools/VCS.py
@@ -88,8 +88,10 @@ class VCS(Bcfg2.Client.Tools.Tool):
return False
try:
- client, path = dulwich.client.get_transport_and_path(entry.get('sourceurl'))
- remote_refs = client.fetch_pack(path, (lambda x: None), None, None, None)
+ client, path = dulwich.client.get_transport_and_path(
+ entry.get('sourceurl'))
+ remote_refs = client.fetch_pack(path,
+ (lambda x: None), None, None, None)
if expected_rev in remote_refs:
expected_rev = remote_refs[expected_rev]
except:
@@ -119,10 +121,12 @@ class VCS(Bcfg2.Client.Tools.Tool):
dulwich.file.ensure_dir_exists(destname)
destr = dulwich.repo.Repo.init(destname)
- cl, host_path = dulwich.client.get_transport_and_path(entry.get('sourceurl'))
+ determine_wants = destr.object_store.determine_wants_all
+ cl, host_path = dulwich.client.get_transport_and_path(
+ entry.get('sourceurl'))
remote_refs = cl.fetch(host_path,
destr,
- determine_wants=destr.object_store.determine_wants_all,
+ determine_wants=determine_wants,
progress=sys.stdout.write)
if entry.get('revision') in remote_refs:
diff --git a/src/lib/Bcfg2/Client/Tools/YUM.py b/src/lib/Bcfg2/Client/Tools/YUM.py
index d1fcb0f4a..ade4da5b3 100644
--- a/src/lib/Bcfg2/Client/Tools/YUM.py
+++ b/src/lib/Bcfg2/Client/Tools/YUM.py
@@ -3,6 +3,7 @@
import copy
import os.path
import sys
+import logging
import yum
import yum.packages
import yum.rpmtrans
@@ -10,8 +11,10 @@ import yum.callbacks
import yum.Errors
import yum.misc
import rpmUtils.arch
+import rpmUtils.miscutils
import Bcfg2.Client.XML
import Bcfg2.Client.Tools
+import Bcfg2.Options
def build_yname(pkgname, inst):
@@ -65,13 +68,13 @@ class RPMDisplay(yum.rpmtrans.RPMBaseCallback):
"""We subclass the default RPM transaction callback so that we
can control Yum's verbosity and pipe it through the right logger."""
- def __init__(self, logger):
+ def __init__(self):
yum.rpmtrans.RPMBaseCallback.__init__(self)
# we want to log events to *both* the Bcfg2 logger (which goes
# to stderr or syslog or wherever the user wants it to go)
# *and* the yum file logger, which will go to yum.log (ticket
# #1103)
- self.bcfg2_logger = logger
+ self.bcfg2_logger = logging.getLogger(self.__class__.__name__)
self.state = None
self.package = None
@@ -110,13 +113,50 @@ class YumDisplay(yum.callbacks.ProcessTransBaseCallback):
"""Class to handle display of what step we are in the Yum transaction
such as downloading packages, etc."""
- def __init__(self, logger):
+ def __init__(self):
yum.callbacks.ProcessTransBaseCallback.__init__(self)
- self.logger = logger
+ self.logger = logging.getLogger(self.__class__.__name__)
class YUM(Bcfg2.Client.Tools.PkgTool):
"""Support for Yum packages."""
+
+ options = Bcfg2.Client.Tools.PkgTool.options + [
+ Bcfg2.Options.BooleanOption(
+ cf=('YUM', 'pkg_checks'), default=True, dest="yum_pkg_checks",
+ help="Perform YUM package checks"),
+ Bcfg2.Options.BooleanOption(
+ cf=('YUM', 'pkg_verify'), default=True, dest="yum_pkg_verify",
+ help="Perform YUM package verify"),
+ Bcfg2.Options.BooleanOption(
+ cf=('YUM', 'install_missing'), default=True,
+ dest="yum_install_missing",
+ help="Install missing packages"),
+ Bcfg2.Options.Option(
+ cf=('YUM', 'erase_flags'), default=["allmatches"],
+ dest="yum_erase_flags", type=Bcfg2.Options.Types.comma_list,
+ help="YUM erase flags"),
+ Bcfg2.Options.BooleanOption(
+ cf=('YUM', 'fix_version'), default=True,
+ dest="yum_fix_version",
+ help="Fix (upgrade or downgrade) packages with the wrong version"),
+ Bcfg2.Options.BooleanOption(
+ cf=('YUM', 'reinstall_broken'), default=True,
+ dest="yum_reinstall_broken",
+ help="Reinstall packages that fail to verify"),
+ Bcfg2.Options.Option(
+ cf=('YUM', 'verify_flags'), default=[],
+ dest="yum_verify_flags", type=Bcfg2.Options.Types.comma_list,
+ help="YUM verify flags"),
+ Bcfg2.Options.Option(
+ cf=('YUM', 'disabled_plugins'), default=[],
+ type=Bcfg2.Options.Types.comma_list, dest="yum_disabled_plugins",
+ help="YUM disabled plugins"),
+ Bcfg2.Options.Option(
+ cf=('YUM', 'enabled_plugins'), default=[],
+ type=Bcfg2.Options.Types.comma_list, dest="yum_enabled_plugins",
+ help="YUM enabled plugins")]
+
pkgtype = 'yum'
__execs__ = []
__handles__ = [('Package', 'yum'),
@@ -126,11 +166,11 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
__req__ = {'Package': ['type'],
'Path': ['type']}
- conflicts = ['YUM24', 'RPM', 'RPMng', 'YUMng']
+ conflicts = ['RPM']
- def __init__(self, logger, setup, config):
- self.yumbase = self._loadYumBase(setup=setup, logger=logger)
- Bcfg2.Client.Tools.PkgTool.__init__(self, logger, setup, config)
+ def __init__(self, config):
+ self.yumbase = self._loadYumBase()
+ Bcfg2.Client.Tools.PkgTool.__init__(self, config)
self.ignores = []
for struct in config:
self.ignores.extend([entry.get('name')
@@ -171,60 +211,56 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
else:
dest[pname] = dict(data)
- # Process the Yum section from the config file. These are all
- # boolean flags, either we do stuff or we don't
- self.pkg_checks = self.setup["yum_pkg_checks"]
- self.pkg_verify = self.setup["yum_pkg_verify"]
- self.do_install = self.setup["yum_installed_action"] == "install"
- self.do_upgrade = self.setup["yum_version_fail_action"] == "upgrade"
- self.do_reinst = self.setup["yum_verify_fail_action"] == "reinstall"
- self.verify_flags = self.setup["yum_verify_flags"]
-
self.installonlypkgs = self.yumbase.conf.installonlypkgs
if 'gpg-pubkey' not in self.installonlypkgs:
self.installonlypkgs.append('gpg-pubkey')
- self.logger.debug("Yum: Install missing: %s" % self.do_install)
- self.logger.debug("Yum: pkg_checks: %s" % self.pkg_checks)
- self.logger.debug("Yum: pkg_verify: %s" % self.pkg_verify)
- self.logger.debug("Yum: Upgrade on version fail: %s" % self.do_upgrade)
- self.logger.debug("Yum: Reinstall on verify fail: %s" % self.do_reinst)
+ self.logger.debug("Yum: Install missing: %s" %
+ Bcfg2.Options.setup.yum_install_missing)
+ self.logger.debug("Yum: pkg_checks: %s" %
+ Bcfg2.Options.setup.yum_pkg_checks)
+ self.logger.debug("Yum: pkg_verify: %s" %
+ Bcfg2.Options.setup.yum_pkg_verify)
+ self.logger.debug("Yum: Upgrade on version fail: %s" %
+ Bcfg2.Options.setup.yum_fix_version)
+ self.logger.debug("Yum: Reinstall on verify fail: %s" %
+ Bcfg2.Options.setup.yum_reinstall_broken)
self.logger.debug("Yum: installonlypkgs: %s" % self.installonlypkgs)
- self.logger.debug("Yum: verify_flags: %s" % self.verify_flags)
- self.logger.debug("Yum: disabled_plugins: %s" %
- self.setup["yum_disabled_plugins"])
- self.logger.debug("Yum: enabled_plugins: %s" %
- self.setup["yum_enabled_plugins"])
-
- def _loadYumBase(self, setup=None, logger=None):
+ self.logger.debug("Yum: verify_flags: %s" %
+ Bcfg2.Options.setup.yum_verify_flags)
+ self.logger.debug("Yum: disabled_plugins: %s" %
+ Bcfg2.Options.setup.yum_disabled_plugins)
+ self.logger.debug("Yum: enabled_plugins: %s" %
+ Bcfg2.Options.setup.yum_enabled_plugins)
+
+ def _loadYumBase(self):
''' this may be called before PkgTool.__init__() is called on
this object (when the YUM object is first instantiated;
PkgTool.__init__() calls RefreshPackages(), which requires a
YumBase object already exist), or after __init__() has
completed, when we reload the yum config before installing
- packages. Consequently, we support both methods by allowing
- setup and logger, the only object properties we use in this
- function, to be passed as keyword arguments or to be omitted
- and drawn from the object itself.'''
+ packages. '''
rv = yum.YumBase() # pylint: disable=C0103
- if setup is None:
- setup = self.setup
- if logger is None:
+ if hasattr(self, "logger"):
logger = self.logger
+ else:
+ logger = logging.getLogger(self.name)
- if setup['debug']:
+ if Bcfg2.Options.setup.debug:
debuglevel = 3
- elif setup['verbose']:
+ elif Bcfg2.Options.setup.verbose:
debuglevel = 2
else:
debuglevel = 0
- if setup['yum_disabled_plugins']:
- rv.preconf.disabled_plugins = setup['yum_disabled_plugins']
+ if len(Bcfg2.Options.setup.yum_disabled_plugins) > 0:
+ rv.preconf.disabled_plugins = \
+ Bcfg2.Options.setup.yum_disabled_plugins
- if setup['yum_enabled_plugins']:
- rv.preconf.enabled_plugins = setup['yum_enabled_plugins']
+ if len(Bcfg2.Options.setup.yum_enabled_plugins) > 0:
+ rv.preconf.enabled_plugins = \
+ Bcfg2.Options.setup.yum_enabled_plugins
# pylint: disable=E1121,W0212
try:
@@ -252,7 +288,7 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
to the newest available """
# old style entry; synthesize Instances from current installed
if (entry.get('name') not in self.yum_installed and
- entry.get('name') not in self.yum_avail):
+ entry.get('name') not in self.yum_avail):
# new entry; fall back to default
entry.set('version', 'any')
else:
@@ -306,7 +342,7 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
missing = Bcfg2.Client.Tools.PkgTool.missing_attrs(self, entry)
if (entry.get('name', None) is None and
- entry.get('group', None) is None):
+ entry.get('group', None) is None):
missing += ['name', 'group']
return missing
@@ -321,7 +357,7 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
using. Disabling file checksums is a new feature yum
3.2.17-ish """
try:
- return pkg.verify(fast=self.setup.get('quick', False))
+ return pkg.verify(fast=Bcfg2.Options.setup.quick)
except TypeError:
# Older Yum API
return pkg.verify()
@@ -446,9 +482,9 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
package_fail = False
qtext_versions = []
virt_pkg = False
- pkg_checks = (self.pkg_checks and
+ pkg_checks = (Bcfg2.Options.setup.yum_pkg_checks and
entry.get('pkg_checks', 'true').lower() == 'true')
- pkg_verify = (self.pkg_verify and
+ pkg_verify = (Bcfg2.Options.setup.yum_pkg_verify and
entry.get('pkg_verify', 'true').lower() == 'true')
yum_group = False
@@ -541,7 +577,7 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
inst.get('verify_flags').lower().replace(' ',
',').split(',')
else:
- verify_flags = self.verify_flags
+ verify_flags = Bcfg2.Options.setup.yum_verify_flags
if 'arch' in nevra:
# If arch is specified use it to select the package
@@ -625,7 +661,7 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
nevra.get('release', 'any'))
entry.set('current_version', "%s:%s-%s" % current_evr)
entry.set('version', "%s:%s-%s" % wanted_evr)
- if yum.compareEVR(current_evr, wanted_evr) == 1:
+ if rpmUtils.miscutils.compareEVR(current_evr, wanted_evr) == 1:
entry.set("package_fail_action", "downgrade")
else:
entry.set("package_fail_action", "update")
@@ -633,7 +669,7 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
qtext_versions.append("U(%s)" % str(all_pkg_objs[0]))
continue
- if self.setup.get('quick', False):
+ if Bcfg2.Options.setup.quick:
# Passed -q on the command line
continue
if not (pkg_verify and
@@ -707,7 +743,7 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
install_only = False
if virt_pkg or \
- (install_only and not self.setup['kevlar']) or \
+ (install_only and not Bcfg2.Options.setup.kevlar) or \
yum_group:
# virtual capability supplied, we are probably dealing
# with multiple packages of different names. This check
@@ -830,8 +866,8 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
self.yumbase.closeRpmDB()
self.RefreshPackages()
- rpm_display = RPMDisplay(self.logger)
- yum_display = YumDisplay(self.logger)
+ rpm_display = RPMDisplay()
+ yum_display = YumDisplay()
# Run the Yum Transaction
try:
rescode, restring = self.yumbase.buildTransaction()
@@ -880,7 +916,7 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
cleanup()
- def Install(self, packages, states): # pylint: disable=R0912,R0914,R0915
+ def Install(self, packages): # pylint: disable=R0912,R0914,R0915
""" Try and fix everything that Yum.VerifyPackages() found
wrong for each Package Entry. This can result in individual
RPMs being installed (for the first time), deleted, downgraded
@@ -898,6 +934,7 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
entry is set to True. """
self.logger.debug('Running Yum.Install()')
+ states = dict()
install_pkgs = []
gpg_keys = []
upgrade_pkgs = []
@@ -915,8 +952,7 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
# Remove extra instances.
# Can not reverify because we don't have a package entry.
if self.extra_instances is not None and len(self.extra_instances) > 0:
- if (self.setup.get('remove') == 'all' or
- self.setup.get('remove') == 'packages'):
+ if Bcfg2.Options.setup.remove in ['all', 'packages']:
self.Remove(self.extra_instances)
else:
self.logger.info("The following extra package instances will "
@@ -941,14 +977,17 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
nevra2string(build_yname(pkg.get('name'), inst)))
continue
status = self.instance_status[inst]
- if not status.get('installed', False) and self.do_install:
+ if not status.get('installed', False) and \
+ Bcfg2.Options.setup.yum_install_missing:
queue_pkg(pkg, inst, install_pkgs)
- elif status.get('version_fail', False) and self.do_upgrade:
+ elif (status.get('version_fail', False) and
+ Bcfg2.Options.setup.yum_fix_version):
if pkg.get("package_fail_action") == "downgrade":
queue_pkg(pkg, inst, downgrade_pkgs)
else:
queue_pkg(pkg, inst, upgrade_pkgs)
- elif status.get('verify_fail', False) and self.do_reinst:
+ elif (status.get('verify_fail', False) and
+ Bcfg2.Options.setup.yum_reinstall_broken):
queue_pkg(pkg, inst, reinstall_pkgs)
else:
# Either there was no Install/Version/Verify
@@ -1037,7 +1076,7 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
self._runYumTransaction()
- if not self.setup['kevlar']:
+ if not Bcfg2.Options.setup.kevlar:
for pkg_entry in [p for p in packages if self.canVerify(p)]:
self.logger.debug("Reverifying Failed Package %s" %
pkg_entry.get('name'))
@@ -1045,8 +1084,8 @@ class YUM(Bcfg2.Client.Tools.PkgTool):
self.VerifyPackage(pkg_entry,
self.modlists.get(pkg_entry, []))
- for entry in [ent for ent in packages if states[ent]]:
- self.modified.append(entry)
+ self.modified.extend(ent for ent in packages if states[ent])
+ return states
def Remove(self, packages):
"""
diff --git a/src/lib/Bcfg2/Client/Tools/YUM24.py b/src/lib/Bcfg2/Client/Tools/YUM24.py
deleted file mode 100644
index d78127ddd..000000000
--- a/src/lib/Bcfg2/Client/Tools/YUM24.py
+++ /dev/null
@@ -1,399 +0,0 @@
-"""This provides bcfg2 support for yum."""
-
-import copy
-import os.path
-import sys
-import yum
-import Bcfg2.Client.XML
-from Bcfg2.Client.Tools.RPM import RPM
-
-
-def build_yname(pkgname, inst):
- """Build yum appropriate package name."""
- ypname = pkgname
- if inst.get('version') != 'any':
- ypname += '-'
- if inst.get('epoch', False):
- ypname += "%s:" % inst.get('epoch')
- if inst.get('version', False) and inst.get('version') != 'any':
- ypname += "%s" % (inst.get('version'))
- if inst.get('release', False) and inst.get('release') != 'any':
- ypname += "-%s" % (inst.get('release'))
- if inst.get('arch', False) and inst.get('arch') != 'any':
- ypname += ".%s" % (inst.get('arch'))
- return ypname
-
-
-class YUM24(RPM):
- """Support for Yum packages."""
- pkgtype = 'yum'
- deprecated = True
- __execs__ = ['/usr/bin/yum', '/var/lib/rpm']
- __handles__ = [('Package', 'yum'),
- ('Package', 'rpm'),
- ('Path', 'ignore')]
-
- __req__ = {'Package': ['name', 'version']}
- __ireq__ = {'Package': ['name']}
- #__ireq__ = {'Package': ['name', 'version']}
-
- __new_req__ = {'Package': ['name'],
- 'Instance': ['version', 'release', 'arch']}
- __new_ireq__ = {'Package': ['name'], \
- 'Instance': []}
- #__new_ireq__ = {'Package': ['name', 'uri'], \
- # 'Instance': ['simplefile', 'version', 'release', 'arch']}
-
- __gpg_req__ = {'Package': ['name', 'version']}
- __gpg_ireq__ = {'Package': ['name', 'version']}
-
- __new_gpg_req__ = {'Package': ['name'],
- 'Instance': ['version', 'release']}
- __new_gpg_ireq__ = {'Package': ['name'],
- 'Instance': ['version', 'release']}
-
- def __init__(self, logger, setup, config):
- RPM.__init__(self, logger, setup, config)
- self.__important__ = self.__important__ + \
- [entry.get('name') for struct in config \
- for entry in struct \
- if entry.tag in ['Path', 'ConfigFile'] and \
- (entry.get('name').startswith('/etc/yum.d') \
- or entry.get('name').startswith('/etc/yum.repos.d')) \
- or entry.get('name') == '/etc/yum.conf']
- self.autodep = setup.get("yum24_autodep")
- self.yum_avail = dict()
- self.yum_installed = dict()
- self.yb = yum.YumBase()
- self.yb.doConfigSetup()
- self.yb.doTsSetup()
- self.yb.doRpmDBSetup()
- yup = self.yb.doPackageLists(pkgnarrow='updates')
- if hasattr(self.yb.rpmdb, 'pkglist'):
- yinst = self.yb.rpmdb.pkglist
- else:
- yinst = self.yb.rpmdb.getPkgList()
- for dest, source in [(self.yum_avail, yup.updates),
- (self.yum_installed, yinst)]:
- for pkg in source:
- if dest is self.yum_avail:
- pname = pkg.name
- data = {pkg.arch: (pkg.epoch, pkg.version, pkg.release)}
- else:
- pname = pkg[0]
- if pkg[1] is None:
- a = 'noarch'
- else:
- a = pkg[1]
- if pkg[2] is None:
- e = '0'
- else:
- e = pkg[2]
- data = {a: (e, pkg[3], pkg[4])}
- if pname in dest:
- dest[pname].update(data)
- else:
- dest[pname] = dict(data)
-
- def VerifyPackage(self, entry, modlist):
- pinned_version = None
- if entry.get('version', False) == 'auto':
- # old style entry; synthesize Instances from current installed
- if entry.get('name') not in self.yum_installed and \
- entry.get('name') not in self.yum_avail:
- # new entry; fall back to default
- entry.set('version', 'any')
- else:
- data = copy.copy(self.yum_installed[entry.get('name')])
- if entry.get('name') in self.yum_avail:
- # installed but out of date
- data.update(self.yum_avail[entry.get('name')])
- for (arch, (epoch, vers, rel)) in list(data.items()):
- x = Bcfg2.Client.XML.SubElement(entry, "Instance",
- name=entry.get('name'),
- version=vers, arch=arch,
- release=rel, epoch=epoch)
- if 'verify_flags' in entry.attrib:
- x.set('verify_flags', entry.get('verify_flags'))
- if 'verify' in entry.attrib:
- x.set('verify', entry.get('verify'))
-
- if entry.get('type', False) == 'yum':
- # Check for virtual provides or packages. If we don't have
- # this package use Yum to resolve it to a real package name
- knownPkgs = list(self.yum_installed.keys()) + list(self.yum_avail.keys())
- if entry.get('name') not in knownPkgs:
- # If the package name matches something installed
- # or available the that's the correct package.
- try:
- pkgDict = dict([(i.name, i) for i in \
- self.yb.returnPackagesByDep(entry.get('name'))])
- except yum.Errors.YumBaseError:
- e = sys.exc_info()[1]
- self.logger.error('Yum Error Depsolving for %s: %s' % \
- (entry.get('name'), str(e)))
- pkgDict = {}
-
- if len(pkgDict) > 1:
- # What do we do with multiple packages?
- s = "YUM24: returnPackagesByDep(%s) returned many packages"
- self.logger.info(s % entry.get('name'))
- s = "YUM24: matching packages: %s"
- self.logger.info(s % str(list(pkgDict.keys())))
- pkgs = set(pkgDict.keys()) & set(self.yum_installed.keys())
- if len(pkgs) > 0:
- # Virtual packages matches an installed real package
- pkg = pkgDict[pkgs.pop()]
- s = "YUM24: chosing: %s" % pkg.name
- self.logger.info(s)
- else:
- # What's the right package? This will fail verify
- # and Yum should Do The Right Thing on package install
- pkg = None
- elif len(pkgDict) == 1:
- pkg = list(pkgDict.values())[0]
- else: # len(pkgDict) == 0
- s = "YUM24: returnPackagesByDep(%s) returned no results"
- self.logger.info(s % entry.get('name'))
- pkg = None
-
- if pkg is not None:
- s = "YUM24: remapping virtual package %s to %s"
- self.logger.info(s % (entry.get('name'), pkg.name))
- entry.set('name', pkg.name)
-
- return RPM.VerifyPackage(self, entry, modlist)
-
- def Install(self, packages, states):
- """
- Try and fix everything that YUM24.VerifyPackages() found wrong for
- each Package Entry. This can result in individual RPMs being
- installed (for the first time), deleted, downgraded
- or upgraded.
-
- NOTE: YUM can not reinstall a package that it thinks is already
- installed.
-
- packages is a list of Package Elements that has
- states[<Package Element>] == False
-
- The following effects occur:
- - states{} is conditionally updated for each package.
- - self.installed{} is rebuilt, possibly multiple times.
- - self.instance_status{} is conditionally updated for each instance
- of a package.
- - Each package will be added to self.modified[] if its states{}
- entry is set to True.
-
- """
- self.logger.info('Running YUM24.Install()')
-
- install_pkgs = []
- gpg_keys = []
- upgrade_pkgs = []
-
- # Remove extra instances.
- # Can not reverify because we don't have a package entry.
- if len(self.extra_instances) > 0:
- if (self.setup.get('remove') == 'all' or \
- self.setup.get('remove') == 'packages'):
- self.Remove(self.extra_instances)
- else:
- self.logger.info("The following extra package instances will be removed by the '-r' option:")
- for pkg in self.extra_instances:
- for inst in pkg:
- self.logger.info(" %s %s" % \
- ((pkg.get('name'), self.str_evra(inst))))
-
- # Figure out which instances of the packages actually need something
- # doing to them and place in the appropriate work 'queue'.
- for pkg in packages:
- insts = [pinst for pinst in pkg \
- if pinst.tag in ['Instance', 'Package']]
- if insts:
- for inst in insts:
- if self.FixInstance(inst, self.instance_status[inst]):
- if self.instance_status[inst].get('installed', False) \
- == False:
- if pkg.get('name') == 'gpg-pubkey':
- gpg_keys.append(inst)
- else:
- install_pkgs.append(inst)
- elif self.instance_status[inst].get('version_fail', \
- False) == True:
- upgrade_pkgs.append(inst)
- else:
- install_pkgs.append(pkg)
-
- # Install GPG keys.
- # Alternatively specify the required keys using 'gpgkey' in the
- # repository definition in yum.conf. YUM will install the keys
- # automatically.
- if len(gpg_keys) > 0:
- for inst in gpg_keys:
- self.logger.info("Installing GPG keys.")
- if inst.get('simplefile') is None:
- self.logger.error("GPG key has no simplefile attribute")
- continue
- key_arg = os.path.join(self.instance_status[inst].get('pkg').get('uri'), \
- inst.get('simplefile'))
- if self.cmd.run("rpm --import %s" % key_arg).success:
- self.logger.debug("Unable to install %s-%s" % \
- (self.instance_status[inst].get('pkg').get('name'), \
- self.str_evra(inst)))
- else:
- self.logger.debug("Installed %s-%s-%s" % \
- (self.instance_status[inst].get('pkg').get('name'), \
- inst.get('version'), inst.get('release')))
- self.RefreshPackages()
- self.gpg_keyids = self.getinstalledgpg()
- pkg = self.instance_status[gpg_keys[0]].get('pkg')
- states[pkg] = self.VerifyPackage(pkg, [])
-
- # Install packages.
- if len(install_pkgs) > 0:
- self.logger.info("Attempting to install packages")
-
- if self.autodep:
- pkgtool = "/usr/bin/yum -d0 -y install %s"
- else:
- pkgtool = "/usr/bin/yum -d0 install %s"
-
- install_args = []
- for inst in install_pkgs:
- pkg_arg = self.instance_status[inst].get('pkg').get('name')
- install_args.append(build_yname(pkg_arg, inst))
-
- if self.cmd.run(pkgtool % " ".join(install_args)).success:
- # The yum command succeeded. All packages installed.
- self.logger.info("Single Pass for Install Succeeded")
- self.RefreshPackages()
- else:
- # The yum command failed. No packages installed.
- # Try installing instances individually.
- self.logger.error("Single Pass Install of Packages Failed")
- installed_instances = []
- for inst in install_pkgs:
- pkg_arg = build_yname(self.instance_status[inst].get('pkg').get('name'), inst)
-
- if self.cmd.run(pkgtool % pkg_arg).success:
- installed_instances.append(inst)
- else:
- self.logger.debug("%s %s would not install." %
- (self.instance_status[inst].get('pkg').get('name'),
- self.str_evra(inst)))
- self.RefreshPackages()
-
- # Fix upgradeable packages.
- if len(upgrade_pkgs) > 0:
- self.logger.info("Attempting to upgrade packages")
-
- if self.autodep:
- pkgtool = "/usr/bin/yum -d0 -y update %s"
- else:
- pkgtool = "/usr/bin/yum -d0 update %s"
-
- upgrade_args = []
- for inst in upgrade_pkgs:
- pkg_arg = build_yname(self.instance_status[inst].get('pkg').get('name'), inst)
- upgrade_args.append(pkg_arg)
-
- if self.cmd.run(pkgtool % " ".join(upgrade_args)).success:
- # The yum command succeeded. All packages installed.
- self.logger.info("Single Pass for Install Succeeded")
- self.RefreshPackages()
- else:
- # The yum command failed. No packages installed.
- # Try installing instances individually.
- self.logger.error("Single Pass Install of Packages Failed")
- installed_instances = []
- for inst in upgrade_pkgs:
- pkg_arg = build_yname(self.instance_status[inst].get('pkg').get('name'), inst)
- if self.cmd.run(pkgtool % pkg_arg).success:
- installed_instances.append(inst)
- else:
- self.logger.debug("%s %s would not install." % \
- (self.instance_status[inst].get('pkg').get('name'), \
- self.str_evra(inst)))
-
- self.RefreshPackages()
-
- if not self.setup['kevlar']:
- for pkg_entry in [p for p in packages if self.canVerify(p)]:
- self.logger.debug("Reverifying Failed Package %s" % (pkg_entry.get('name')))
- states[pkg_entry] = self.VerifyPackage(pkg_entry, \
- self.modlists.get(pkg_entry, []))
-
- for entry in [ent for ent in packages if states[ent]]:
- self.modified.append(entry)
-
- def Remove(self, packages):
- """
- Remove specified entries.
-
- packages is a list of Package Entries with Instances generated
- by FindExtra().
- """
- self.logger.debug('Running YUM24.Remove()')
-
- if self.autodep:
- pkgtool = "/usr/bin/yum -d0 -y erase %s"
- else:
- pkgtool = "/usr/bin/yum -d0 erase %s"
-
- erase_args = []
- for pkg in packages:
- for inst in pkg:
- if pkg.get('name') != 'gpg-pubkey':
- pkg_arg = pkg.get('name') + '-'
- if inst.get('epoch', False):
- pkg_arg = pkg_arg + inst.get('epoch') + ':'
- pkg_arg = pkg_arg + inst.get('version') + '-' + inst.get('release')
- if inst.get('arch', False):
- pkg_arg = pkg_arg + '.' + inst.get('arch')
- erase_args.append(pkg_arg)
- else:
- pkgspec = {'name': pkg.get('name'),
- 'version': inst.get('version'),
- 'release': inst.get('release')}
- self.logger.info("WARNING: gpg-pubkey package not in configuration %s %s"\
- % (pkgspec.get('name'), self.str_evra(pkgspec)))
- self.logger.info(" This package will be deleted in a future version of the YUM24 driver.")
-
- rv = self.cmd.run(pkgtool % " ".join(erase_args))
- if rv.success:
- self.modified += packages
- for pkg in erase_args:
- self.logger.info("Deleted %s" % (pkg))
- else:
- self.logger.info("Bulk erase failed with errors:")
- self.logger.debug("Erase results: %s" % rv.error)
- self.logger.info("Attempting individual erase for each package.")
- for pkg in packages:
- pkg_modified = False
- for inst in pkg:
- if pkg.get('name') != 'gpg-pubkey':
- pkg_arg = pkg.get('name') + '-'
- if 'epoch' in inst.attrib:
- pkg_arg = pkg_arg + inst.get('epoch') + ':'
- pkg_arg = pkg_arg + inst.get('version') + '-' + inst.get('release')
- if 'arch' in inst.attrib:
- pkg_arg = pkg_arg + '.' + inst.get('arch')
- else:
- self.logger.info("WARNING: gpg-pubkey package not in configuration %s %s"\
- % (pkg.get('name'), self.str_evra(pkg)))
- self.logger.info(" This package will be deleted in a future version of the YUM24 driver.")
- continue
-
- rv = self.cmd.run(self.pkgtool % pkg_arg)
- if rv.success:
- pkg_modified = True
- self.logger.info("Deleted %s" % pkg_arg)
- else:
- self.logger.error("Unable to delete %s" % pkg_arg)
- self.logger.debug("Failure: %s" % rv.error)
- if pkg_modified == True:
- self.modified.append(pkg)
-
- self.RefreshPackages()
- self.extra = self.FindExtra()
diff --git a/src/lib/Bcfg2/Client/Tools/YUMng.py b/src/lib/Bcfg2/Client/Tools/YUMng.py
deleted file mode 100644
index 22fbba537..000000000
--- a/src/lib/Bcfg2/Client/Tools/YUMng.py
+++ /dev/null
@@ -1,9 +0,0 @@
-""" YUM driver called 'YUMng' for backwards compat """
-
-from Bcfg2.Client.Tools.YUM import YUM
-
-
-class YUMng(YUM):
- """ YUM driver called 'YUMng' for backwards compat """
- deprecated = True
- conflicts = ['YUM24', 'RPM', 'RPMng']
diff --git a/src/lib/Bcfg2/Client/Tools/__init__.py b/src/lib/Bcfg2/Client/Tools/__init__.py
index b5bfdb5de..2e3421840 100644
--- a/src/lib/Bcfg2/Client/Tools/__init__.py
+++ b/src/lib/Bcfg2/Client/Tools/__init__.py
@@ -1,25 +1,13 @@
"""This contains all Bcfg2 Tool modules"""
import os
-import stat
import sys
-
+import stat
+import logging
+import Bcfg2.Options
import Bcfg2.Client
import Bcfg2.Client.XML
-from Bcfg2.Client.Frame import matches_white_list, passes_black_list
from Bcfg2.Utils import Executor, ClassName
-from Bcfg2.Compat import walk_packages # pylint: disable=W0622
-
-__all__ = [m[1] for m in walk_packages(path=__path__)]
-
-# pylint: disable=C0103
-#: All available tools
-drivers = [item for item in __all__ if item not in ['rpmtools']]
-
-#: The default set of tools that will be used if "drivers" is not set
-#: in bcfg2.conf
-default = drivers[:]
-# pylint: enable=C0103
class ToolInstantiationError(Exception):
@@ -37,6 +25,12 @@ class Tool(object):
.. autoattribute:: Bcfg2.Client.Tools.Tool.__important__
"""
+ options = [
+ Bcfg2.Options.Option(
+ cf=('client', 'command_timeout'),
+ help="Timeout when running external commands other than probes",
+ type=Bcfg2.Options.Types.timeout)]
+
#: The name of the tool. By default this uses
#: :class:`Bcfg2.Client.Tools.ClassName` to ensure that it is the
#: same as the name of the class.
@@ -80,30 +74,22 @@ class Tool(object):
#: runtime with a warning.
conflicts = []
- def __init__(self, logger, setup, config):
+ def __init__(self, config):
"""
- :param logger: Logger that will be used for logging by this tool
- :type logger: logging.Logger
- :param setup: The option set Bcfg2 was invoked with
- :type setup: Bcfg2.Options.OptionParser
:param config: The XML configuration for this client
:type config: lxml.etree._Element
:raises: :exc:`Bcfg2.Client.Tools.ToolInstantiationError`
"""
- #: A :class:`Bcfg2.Options.OptionParser` object describing the
- #: option set Bcfg2 was invoked with
- self.setup = setup
-
#: A :class:`logging.Logger` object that will be used by this
#: tool for logging
- self.logger = logger
+ self.logger = logging.getLogger(self.name)
#: The XML configuration for this client
self.config = config
#: An :class:`Bcfg2.Utils.Executor` object for
#: running external commands.
- self.cmd = Executor(timeout=self.setup['command_timeout'])
+ self.cmd = Executor(timeout=Bcfg2.Options.setup.command_timeout)
#: A list of entries that have been modified by this tool
self.modified = []
@@ -124,7 +110,7 @@ class Tool(object):
for struct in self.config:
for entry in struct:
if (entry.tag == 'Path' and
- entry.get('important', 'false').lower() == 'true'):
+ entry.get('important', 'false').lower() == 'true'):
self.__important__.append(entry.get('name'))
self.handled = self.getSupportedEntries()
@@ -146,39 +132,41 @@ class Tool(object):
def _install_allowed(self, entry):
""" Return true if the given entry is allowed to be installed by
the whitelist or blacklist """
- if self.setup['decision'] == 'whitelist' and \
- not matches_white_list(entry, self.setup['decision_list']):
- self.logger.info("In whitelist mode: suppressing %s: %s" %
- (entry.tag, entry.get('name')))
+ if (Bcfg2.Options.setup.decision == 'whitelist' and
+ not Bcfg2.Client.matches_white_list(
+ entry, Bcfg2.Options.setup.decision_list)):
+ self.logger.info("In whitelist mode: suppressing Action: %s" %
+ entry.get('name'))
return False
- if self.setup['decision'] == 'blacklist' and \
- not passes_black_list(entry, self.setup['decision_list']):
- self.logger.info("In blacklist mode: suppressing %s: %s" %
- (entry.tag, entry.get('name')))
+ if (Bcfg2.Options.setup.decision == 'blacklist' and
+ not Bcfg2.Client.passes_black_list(
+ entry, Bcfg2.Options.setup.decision_list)):
+ self.logger.info("In blacklist mode: suppressing Action: %s" %
+ entry.get('name'))
return False
return True
- def BundleUpdated(self, bundle, states): # pylint: disable=W0613
+ def BundleUpdated(self, bundle): # pylint: disable=W0613
""" Callback that is invoked when a bundle has been updated.
:param bundle: The bundle that has been updated
:type bundle: lxml.etree._Element
- :param states: The :attr:`Bcfg2.Client.Frame.Frame.states` dict
- :type states: dict
- :returns: None """
- return
+ :returns: dict - A dict of the state of entries suitable for
+ updating :attr:`Bcfg2.Client.Client.states`
+ """
+ return dict()
- def BundleNotUpdated(self, bundle, states): # pylint: disable=W0613
+ def BundleNotUpdated(self, bundle): # pylint: disable=W0613
""" Callback that is invoked when a bundle has been updated.
:param bundle: The bundle that has been updated
:type bundle: lxml.etree._Element
- :param states: The :attr:`Bcfg2.Client.Frame.Frame.states` dict
- :type states: dict
- :returns: None """
- return
+ :returns: dict - A dict of the state of entries suitable for
+ updating :attr:`Bcfg2.Client.Client.states`
+ """
+ return dict()
- def Inventory(self, states, structures=None):
+ def Inventory(self, structures=None):
""" Take an inventory of the system as it exists. This
involves two steps:
@@ -193,18 +181,19 @@ class Tool(object):
is the entry tag. E.g., a Path entry would be verified by
calling :func:`VerifyPath`.
- :param states: The :attr:`Bcfg2.Client.Frame.Frame.states` dict
- :type states: dict
:param structures: The list of structures (i.e., bundles) to
get entries from. If this is not given,
all children of
:attr:`Bcfg2.Client.Tools.Tool.config` will
be used.
:type structures: list of lxml.etree._Element
- :returns: None """
+ :returns: dict - A dict of the state of entries suitable for
+ updating :attr:`Bcfg2.Client.Client.states`
+ """
if not structures:
structures = self.config.getchildren()
mods = self.buildModlist()
+ states = dict()
for struct in structures:
for entry in struct.getchildren():
if self.canVerify(entry):
@@ -216,14 +205,17 @@ class Tool(object):
continue
try:
states[entry] = func(entry, mods)
+ except KeyboardInterrupt:
+ raise
except: # pylint: disable=W0702
self.logger.error("%s: Unexpected failure verifying %s"
% (self.name,
self.primarykey(entry)),
exc_info=1)
self.extra = self.FindExtra()
+ return states
- def Install(self, entries, states):
+ def Install(self, entries):
""" Install entries. 'Install' in this sense means either
initially install, or update as necessary to match the
specification.
@@ -235,9 +227,10 @@ class Tool(object):
:param entries: The entries to install
:type entries: list of lxml.etree._Element
- :param states: The :attr:`Bcfg2.Client.Frame.Frame.states` dict
- :type states: dict
- :returns: None """
+ :returns: dict - A dict of the state of entries suitable for
+ updating :attr:`Bcfg2.Client.Client.states`
+ """
+ states = dict()
for entry in entries:
try:
func = getattr(self, "Install%s" % entry.tag)
@@ -253,6 +246,7 @@ class Tool(object):
self.logger.error("%s: Unexpected failure installing %s" %
(self.name, self.primarykey(entry)),
exc_info=1)
+ return states
def Remove(self, entries):
""" Remove specified extra entries.
@@ -413,8 +407,8 @@ class PkgTool(Tool):
#: The ``type`` attribute of Packages handled by this tool.
pkgtype = 'echo'
- def __init__(self, logger, setup, config):
- Tool.__init__(self, logger, setup, config)
+ def __init__(self, config):
+ Tool.__init__(self, config)
#: A dict of installed packages; the keys should be package
#: names and the values should be simple strings giving the
@@ -451,32 +445,27 @@ class PkgTool(Tool):
for pkg in packages)
return self.pkgtool[0] % pkgargs
- def Install(self, packages, states):
+ def Install(self, packages):
""" Run a one-pass install where all required packages are
installed with a single command, followed by single package
installs in case of failure.
:param entries: The entries to install
:type entries: list of lxml.etree._Element
- :param states: The :attr:`Bcfg2.Client.Frame.Frame.states` dict
- :type states: dict
- :returns: None """
+ :returns: dict - A dict of the state of entries suitable for
+ updating :attr:`Bcfg2.Client.Client.states`
+ """
self.logger.info("Trying single pass package install for pkgtype %s" %
self.pkgtype)
- pkgcmd = self._get_package_command(packages)
- self.logger.debug("Running command: %s" % pkgcmd)
- if self.cmd.run(pkgcmd):
+ states = dict()
+ if self.cmd.run(self._get_package_command(packages)):
self.logger.info("Single Pass Succeded")
# set all package states to true and flush workqueues
- pkgnames = [pkg.get('name') for pkg in packages]
- for entry in list(states.keys()):
- if (entry.tag == 'Package' and
- entry.get('type') == self.pkgtype and
- entry.get('name') in pkgnames):
- self.logger.debug('Setting state to true for pkg %s' %
- entry.get('name'))
- states[entry] = True
+ for entry in packages:
+ self.logger.debug('Setting state to true for %s' %
+ self.primarykey(entry))
+ states[entry] = True
self.RefreshPackages()
else:
self.logger.error("Single Pass Failed")
@@ -494,10 +483,13 @@ class PkgTool(Tool):
if self.cmd.run(self._get_package_command([pkg])):
states[pkg] = True
else:
+ states[pkg] = False
self.logger.error("Failed to install package %s" %
pkg.get('name'))
self.RefreshPackages()
- self.modified.extend(entry for entry in packages if states[entry])
+ self.modified.extend(entry for entry in packages
+ if entry in states and states[entry])
+ return states
def RefreshPackages(self):
""" Refresh the internal representation of the package
@@ -511,7 +503,8 @@ class PkgTool(Tool):
extras = [data for data in list(self.installed.items())
if data[0] not in packages]
return [Bcfg2.Client.XML.Element('Package', name=name,
- type=self.pkgtype, version=version)
+ type=self.pkgtype,
+ current_version=version)
for (name, version) in extras]
FindExtra.__doc__ = Tool.FindExtra.__doc__
@@ -519,8 +512,14 @@ class PkgTool(Tool):
class SvcTool(Tool):
""" Base class for tools that handle Service entries """
- def __init__(self, logger, setup, config):
- Tool.__init__(self, logger, setup, config)
+ options = Tool.options + [
+ Bcfg2.Options.Option(
+ '-s', '--service-mode', default='default',
+ choices=['default', 'disabled', 'build'],
+ help='Set client service mode')]
+
+ def __init__(self, config):
+ Tool.__init__(self, config)
#: List of services that have been restarted
self.restarted = []
__init__.__doc__ = Tool.__init__.__doc__
@@ -597,14 +596,14 @@ class SvcTool(Tool):
return bool(self.cmd.run(self.get_svc_command(service, 'status')))
def Remove(self, services):
- if self.setup['servicemode'] != 'disabled':
+ if Bcfg2.Options.setup.service_mode != 'disabled':
for entry in services:
entry.set("status", "off")
self.InstallService(entry)
Remove.__doc__ = Tool.Remove.__doc__
- def BundleUpdated(self, bundle, states):
- if self.setup['servicemode'] == 'disabled':
+ def BundleUpdated(self, bundle):
+ if Bcfg2.Options.setup.service_mode == 'disabled':
return
for entry in bundle:
@@ -615,15 +614,16 @@ class SvcTool(Tool):
estatus = entry.get('status')
restart = entry.get("restart", "true").lower()
if (restart == "false" or estatus == 'ignore' or
- (restart == "interactive" and not self.setup['interactive'])):
+ (restart == "interactive" and
+ not Bcfg2.Options.setup.interactive)):
continue
success = False
if estatus == 'on':
- if self.setup['servicemode'] == 'build':
+ if Bcfg2.Options.setup.service_mode == 'build':
success = self.stop_service(entry)
elif entry.get('name') not in self.restarted:
- if self.setup['interactive']:
+ if Bcfg2.Options.setup.interactive:
if not Bcfg2.Client.prompt('Restart service %s? (y/N) '
% entry.get('name')):
continue
@@ -635,9 +635,10 @@ class SvcTool(Tool):
if not success:
self.logger.error("Failed to manipulate service %s" %
(entry.get('name')))
+ return dict()
BundleUpdated.__doc__ = Tool.BundleUpdated.__doc__
- def Install(self, entries, states):
+ def Install(self, entries):
install_entries = []
for entry in entries:
if entry.get('install', 'true').lower() == 'false':
@@ -645,7 +646,7 @@ class SvcTool(Tool):
(entry.tag, entry.get('name')))
else:
install_entries.append(entry)
- return Tool.Install(self, install_entries, states)
+ return Tool.Install(self, install_entries)
Install.__doc__ = Tool.Install.__doc__
def InstallService(self, entry):
diff --git a/src/lib/Bcfg2/Client/Tools/launchd.py b/src/lib/Bcfg2/Client/Tools/launchd.py
index b0661b26b..a4aeab6c7 100644
--- a/src/lib/Bcfg2/Client/Tools/launchd.py
+++ b/src/lib/Bcfg2/Client/Tools/launchd.py
@@ -12,8 +12,8 @@ class launchd(Bcfg2.Client.Tools.Tool): # pylint: disable=C0103
__execs__ = ['/bin/launchctl', '/usr/bin/defaults']
__req__ = {'Service': ['name', 'status']}
- def __init__(self, logger, setup, config):
- Bcfg2.Client.Tools.Tool.__init__(self, logger, setup, config)
+ def __init__(self, config):
+ Bcfg2.Client.Tools.Tool.__init__(self, config)
# Locate plist file that provides given reverse-fqdn name:
#
@@ -117,9 +117,11 @@ class launchd(Bcfg2.Client.Tools.Tool): # pylint: disable=C0103
status='on')
for name in allsrv]
- def BundleUpdated(self, bundle, states):
+ def BundleUpdated(self, bundle):
"""Reload launchd plist."""
- for entry in [entry for entry in bundle if self.handlesEntry(entry)]:
+ for entry in bundle:
+ if not self.handlesEntry(entry):
+ continue
if not self.canInstall(entry):
self.logger.error("Insufficient information to restart "
"service %s" % entry.get('name'))
diff --git a/src/lib/Bcfg2/Client/Tools/rpmtools.py b/src/lib/Bcfg2/Client/Tools/rpmtools.py
deleted file mode 100755
index 32a04262d..000000000
--- a/src/lib/Bcfg2/Client/Tools/rpmtools.py
+++ /dev/null
@@ -1,1091 +0,0 @@
-#!/usr/bin/env python
-"""
- Module that uses rpm-python to implement the following rpm
- functionality for the bcfg2 RPM and YUM client drivers:
-
- rpm -qa
- rpm --verify
- rpm --erase
-
- The code closely follows the rpm C code.
-
- The code was written to be used in the bcfg2 RPM/YUM drivers.
-
- Some command line options have been provided to assist with
- testing and development, but the output isn't pretty and looks
- nothing like rpm output.
-
- Run 'rpmtools' -h for the options.
-
-"""
-
-import grp
-import optparse
-import os
-import pwd
-import rpm
-import stat
-import sys
-if sys.version_info >= (2, 5):
- import hashlib
- py24compat = False
-else:
- # FIXME: Remove when client python dep is 2.5 or greater
- py24compat = True
- import md5
-
-# Determine what prelink tools we have available.
-# The isprelink module is a python extension that examines the ELF headers
-# to see if the file has been prelinked. If it is not present a lot of files
-# are unnecessarily run through the prelink command.
-try:
- from isprelink import *
- isprelink_imported = True
-except ImportError:
- isprelink_imported = False
-
-# If the prelink command is installed on the system then we need to do
-# prelink -y on files.
-if os.access('/usr/sbin/prelink', os.X_OK):
- prelink_exists = True
-else:
- prelink_exists = False
-
-# If we don't have isprelink then we will use the prelink configuration file to
-# filter what we have to put through prelink -y.
-import re
-blacklist = []
-whitelist = []
-try:
- f = open('/etc/prelink.conf', mode='r')
- for line in f:
- if line.startswith('#'):
- continue
- option, pattern = line.split()
- if pattern.startswith('*.'):
- pattern = pattern.replace('*.', '\.')
- pattern += '$'
- elif pattern.startswith('/'):
- pattern = '^' + pattern
- if option == '-b':
- blacklist.append(pattern)
- elif option == '-l':
- whitelist.append(pattern)
- f.close()
-except IOError:
- pass
-
-blacklist_re = re.compile('|'.join(blacklist))
-whitelist_re = re.compile('|'.join(whitelist))
-
-# Flags that are not defined in rpm-python.
-# They are defined in lib/rpmcli.h
-# Bit(s) for verifyFile() attributes.
-#
-RPMVERIFY_NONE = 0 # /*!< */
-RPMVERIFY_MD5 = 1 # 1 << 0 # /*!< from %verify(md5) */
-RPMVERIFY_FILESIZE = 2 # 1 << 1 # /*!< from %verify(size) */
-RPMVERIFY_LINKTO = 4 # 1 << 2 # /*!< from %verify(link) */
-RPMVERIFY_USER = 8 # 1 << 3 # /*!< from %verify(user) */
-RPMVERIFY_GROUP = 16 # 1 << 4 # /*!< from %verify(group) */
-RPMVERIFY_MTIME = 32 # 1 << 5 # /*!< from %verify(mtime) */
-RPMVERIFY_MODE = 64 # 1 << 6 # /*!< from %verify(mode) */
-RPMVERIFY_RDEV = 128 # 1 << 7 # /*!< from %verify(rdev) */
-RPMVERIFY_CONTEXTS = 32768 # (1 << 15) # /*!< from --nocontexts */
-RPMVERIFY_READLINKFAIL = 268435456 # (1 << 28) # /*!< readlink failed */
-RPMVERIFY_READFAIL = 536870912 # (1 << 29) # /*!< file read failed */
-RPMVERIFY_LSTATFAIL = 1073741824 # (1 << 30) # /*!< lstat failed */
-RPMVERIFY_LGETFILECONFAIL = 2147483648 # (1 << 31) # /*!< lgetfilecon failed */
-
-RPMVERIFY_FAILURES = \
- (RPMVERIFY_LSTATFAIL|RPMVERIFY_READFAIL|RPMVERIFY_READLINKFAIL| \
- RPMVERIFY_LGETFILECONFAIL)
-
-# Bit(s) to control rpm_verify() operation.
-#
-VERIFY_DEFAULT = 0, # /*!< */
-VERIFY_MD5 = 1 << 0 # /*!< from --nomd5 */
-VERIFY_SIZE = 1 << 1 # /*!< from --nosize */
-VERIFY_LINKTO = 1 << 2 # /*!< from --nolinkto */
-VERIFY_USER = 1 << 3 # /*!< from --nouser */
-VERIFY_GROUP = 1 << 4 # /*!< from --nogroup */
-VERIFY_MTIME = 1 << 5 # /*!< from --nomtime */
-VERIFY_MODE = 1 << 6 # /*!< from --nomode */
-VERIFY_RDEV = 1 << 7 # /*!< from --nodev */
-# /* bits 8-14 unused, reserved for rpmVerifyAttrs */
-VERIFY_CONTEXTS = 1 << 15 # /*!< verify: from --nocontexts */
-VERIFY_FILES = 1 << 16 # /*!< verify: from --nofiles */
-VERIFY_DEPS = 1 << 17 # /*!< verify: from --nodeps */
-VERIFY_SCRIPT = 1 << 18 # /*!< verify: from --noscripts */
-VERIFY_DIGEST = 1 << 19 # /*!< verify: from --nodigest */
-VERIFY_SIGNATURE = 1 << 20 # /*!< verify: from --nosignature */
-VERIFY_PATCHES = 1 << 21 # /*!< verify: from --nopatches */
-VERIFY_HDRCHK = 1 << 22 # /*!< verify: from --nohdrchk */
-VERIFY_FOR_LIST = 1 << 23 # /*!< query: from --list */
-VERIFY_FOR_STATE = 1 << 24 # /*!< query: from --state */
-VERIFY_FOR_DOCS = 1 << 25 # /*!< query: from --docfiles */
-VERIFY_FOR_CONFIG = 1 << 26 # /*!< query: from --configfiles */
-VERIFY_FOR_DUMPFILES = 1 << 27 # /*!< query: from --dump */
-# /* bits 28-31 used in rpmVerifyAttrs */
-
-# Comes from C cource. lib/rpmcli.h
-VERIFY_ATTRS = \
- (VERIFY_MD5 | VERIFY_SIZE | VERIFY_LINKTO | VERIFY_USER | VERIFY_GROUP | \
- VERIFY_MTIME | VERIFY_MODE | VERIFY_RDEV | VERIFY_CONTEXTS)
-
-VERIFY_ALL = \
- (VERIFY_ATTRS | VERIFY_FILES | VERIFY_DEPS | VERIFY_SCRIPT | VERIFY_DIGEST |\
- VERIFY_SIGNATURE | VERIFY_HDRCHK)
-
-
-# Some masks for what checks to NOT do on these file types.
-# The C code actiually resets these up for every file.
-DIR_FLAGS = ~(RPMVERIFY_MD5 | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | \
- RPMVERIFY_LINKTO)
-
-# These file types all have the same mask, but hopefully this will make the
-# code more readable.
-FIFO_FLAGS = CHR_FLAGS = BLK_FLAGS = GHOST_FLAGS = DIR_FLAGS
-
-LINK_FLAGS = ~(RPMVERIFY_MD5 | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | \
- RPMVERIFY_MODE | RPMVERIFY_USER | RPMVERIFY_GROUP)
-
-REG_FLAGS = ~(RPMVERIFY_LINKTO)
-
-
-def s_isdev(mode):
- """
- Check to see if a file is a device.
-
- """
- return stat.S_ISBLK(mode) | stat.S_ISCHR(mode)
-
-def rpmpackagelist(rts):
- """
- Equivalent of rpm -qa. Intended for RefreshPackages() in the RPM Driver.
- Requires rpmtransactionset() to be run first to get a ts.
- Returns a list of pkgspec dicts.
-
- e.g. [ {'name':'foo', 'epoch':'20', 'version':'1.2', 'release':'5', 'arch':'x86_64' },
- {'name':'bar', 'epoch':'10', 'version':'5.2', 'release':'2', 'arch':'x86_64' } ]
-
- """
- return [{'name':header[rpm.RPMTAG_NAME],
- 'epoch':header[rpm.RPMTAG_EPOCH],
- 'version':header[rpm.RPMTAG_VERSION],
- 'release':header[rpm.RPMTAG_RELEASE],
- 'arch':header[rpm.RPMTAG_ARCH],
- 'gpgkeyid':header.sprintf("%|SIGGPG?{%{SIGGPG:pgpsig}}:{None}|").split()[-1]}
- for header in rts.dbMatch()]
-
-def getindexbykeyword(index_ts, **kwargs):
- """
- Return list of indexs from the rpmdb matching keywords
- ex: getHeadersByKeyword(name='foo', version='1', release='1')
-
- Can be passed any structure that can be indexed by the pkgspec
- keyswords as other keys are filtered out.
-
- """
- lst = []
- name = kwargs.get('name')
- if name:
- index_mi = index_ts.dbMatch(rpm.RPMTAG_NAME, name)
- else:
- index_mi = index_ts.dbMatch()
-
- if 'epoch' in kwargs:
- if kwargs['epoch'] != None and kwargs['epoch'] != 'None':
- kwargs['epoch'] = int(kwargs['epoch'])
- else:
- del(kwargs['epoch'])
-
- keywords = [key for key in list(kwargs.keys()) \
- if key in ('name', 'epoch', 'version', 'release', 'arch')]
- keywords_len = len(keywords)
- for hdr in index_mi:
- match = 0
- for keyword in keywords:
- if hdr[keyword] == kwargs[keyword]:
- match += 1
- if match == keywords_len:
- lst.append(index_mi.instance())
- del index_mi
- return lst
-
-def getheadersbykeyword(header_ts, **kwargs):
- """
- Borrowed parts of this from from Yum. Need to fix it though.
- Epoch is not handled right.
-
- Return list of headers from the rpmdb matching keywords
- ex: getHeadersByKeyword(name='foo', version='1', release='1')
-
- Can be passed any structure that can be indexed by the pkgspec
- keyswords as other keys are filtered out.
-
- """
- lst = []
- name = kwargs.get('name')
- if name:
- header_mi = header_ts.dbMatch(rpm.RPMTAG_NAME, name)
- else:
- header_mi = header_ts.dbMatch()
-
- if 'epoch' in kwargs:
- if kwargs['epoch'] != None and kwargs['epoch'] != 'None':
- kwargs['epoch'] = int(kwargs['epoch'])
- else:
- del(kwargs['epoch'])
-
- keywords = [key for key in list(kwargs.keys()) \
- if key in ('name', 'epoch', 'version', 'release', 'arch')]
- keywords_len = len(keywords)
- for hdr in header_mi:
- match = 0
- for keyword in keywords:
- if hdr[keyword] == kwargs[keyword]:
- match += 1
- if match == keywords_len:
- lst.append(hdr)
- del header_mi
- return lst
-
-def prelink_md5_check(filename):
- """
- Checks if a file is prelinked. If it is run it through prelink -y
- to get the unprelinked md5 and file size.
-
- Return 0 if the file was not prelinked, otherwise return the file size.
- Always return the md5.
-
- """
- prelink = False
- try:
- plf = open(filename, "rb")
- except IOError:
- return False, 0
-
- if prelink_exists:
- if isprelink_imported:
- plfd = plf.fileno()
- if isprelink(plfd):
- plf.close()
- cmd = '/usr/sbin/prelink -y %s 2> /dev/null' \
- % (re.escape(filename))
- plf = os.popen(cmd, 'rb')
- prelink = True
- elif whitelist_re.search(filename) and not blacklist_re.search(filename):
- plf.close()
- cmd = '/usr/sbin/prelink -y %s 2> /dev/null' \
- % (re.escape(filename))
- plf = os.popen(cmd, 'rb')
- prelink = True
-
- fsize = 0
- if py24compat:
- chksum = md5.new()
- else:
- chksum = hashlib.md5()
- while 1:
- data = plf.read()
- if not data:
- break
- fsize += len(data)
- chksum.update(data)
- plf.close()
- file_md5 = chksum.hexdigest()
- if prelink:
- return file_md5, fsize
- else:
- return file_md5, 0
-
-def prelink_size_check(filename):
- """
- This check is only done if the prelink_md5_check() is not done first.
-
- Checks if a file is prelinked. If it is run it through prelink -y
- to get the unprelinked file size.
-
- Return 0 if the file was not prelinked, otherwise return the file size.
-
- """
- fsize = 0
- try:
- plf = open(filename, "rb")
- except IOError:
- return False
-
- if prelink_exists:
- if isprelink_imported:
- plfd = plf.fileno()
- if isprelink(plfd):
- plf.close()
- cmd = '/usr/sbin/prelink -y %s 2> /dev/null' \
- % (re.escape(filename))
- plf = os.popen(cmd, 'rb')
-
- while 1:
- data = plf.read()
- if not data:
- break
- fsize += len(data)
-
- elif whitelist_re.search(filename) and not blacklist_re.search(filename):
- plf.close()
- cmd = '/usr/sbin/prelink -y %s 2> /dev/null' \
- % (re.escape(filename))
- plf = os.popen(cmd, 'rb')
-
- while 1:
- data = plf.read()
- if not data:
- break
- fsize += len(data)
-
- plf.close()
-
- return fsize
-
-def debug_verify_flags(vflags):
- """
- Decodes the verify flags bits.
- """
- if vflags & RPMVERIFY_MD5:
- print('RPMVERIFY_MD5')
- if vflags & RPMVERIFY_FILESIZE:
- print('RPMVERIFY_FILESIZE')
- if vflags & RPMVERIFY_LINKTO:
- print('RPMVERIFY_LINKTO')
- if vflags & RPMVERIFY_USER:
- print('RPMVERIFY_USER')
- if vflags & RPMVERIFY_GROUP:
- print('RPMVERIFY_GROUP')
- if vflags & RPMVERIFY_MTIME:
- print('RPMVERIFY_MTIME')
- if vflags & RPMVERIFY_MODE:
- print('RPMVERIFY_MODE')
- if vflags & RPMVERIFY_RDEV:
- print('RPMVERIFY_RDEV')
- if vflags & RPMVERIFY_CONTEXTS:
- print('RPMVERIFY_CONTEXTS')
- if vflags & RPMVERIFY_READLINKFAIL:
- print('RPMVERIFY_READLINKFAIL')
- if vflags & RPMVERIFY_READFAIL:
- print('RPMVERIFY_READFAIL')
- if vflags & RPMVERIFY_LSTATFAIL:
- print('RPMVERIFY_LSTATFAIL')
- if vflags & RPMVERIFY_LGETFILECONFAIL:
- print('RPMVERIFY_LGETFILECONFAIL')
-
-def debug_file_flags(fflags):
- """
- Decodes the file flags bits.
- """
- if fflags & rpm.RPMFILE_CONFIG:
- print('rpm.RPMFILE_CONFIG')
-
- if fflags & rpm.RPMFILE_DOC:
- print('rpm.RPMFILE_DOC')
-
- if fflags & rpm.RPMFILE_ICON:
- print('rpm.RPMFILE_ICON')
-
- if fflags & rpm.RPMFILE_MISSINGOK:
- print('rpm.RPMFILE_MISSINGOK')
-
- if fflags & rpm.RPMFILE_NOREPLACE:
- print('rpm.RPMFILE_NOREPLACE')
-
- if fflags & rpm.RPMFILE_GHOST:
- print('rpm.RPMFILE_GHOST')
-
- if fflags & rpm.RPMFILE_LICENSE:
- print('rpm.RPMFILE_LICENSE')
-
- if fflags & rpm.RPMFILE_README:
- print('rpm.RPMFILE_README')
-
- if fflags & rpm.RPMFILE_EXCLUDE:
- print('rpm.RPMFILE_EXLUDE')
-
- if fflags & rpm.RPMFILE_UNPATCHED:
- print('rpm.RPMFILE_UNPATCHED')
-
- if fflags & rpm.RPMFILE_PUBKEY:
- print('rpm.RPMFILE_PUBKEY')
-
-def rpm_verify_file(fileinfo, rpmlinktos, omitmask):
- """
- Verify all the files in a package.
-
- Returns a list of error flags, the file type and file name. The list
- entries are strings that are the same as the labels for the bitwise
- flags used in the C code.
-
- """
- (fname, fsize, fmode, fmtime, fflags, frdev, finode, fnlink, fstate, \
- vflags, fuser, fgroup, fmd5) = fileinfo
-
- # 1. rpmtsRootDir stuff. What does it do and where to I get it from?
-
- file_results = []
- flags = vflags
-
- # Check to see if the file was installed - if not pretend all is ok.
- # This is what the rpm C code does!
- if fstate != rpm.RPMFILE_STATE_NORMAL:
- return file_results
-
- # Get the installed files stats
- try:
- lstat = os.lstat(fname)
- except OSError:
- if not (fflags & (rpm.RPMFILE_MISSINGOK|rpm.RPMFILE_GHOST)):
- file_results.append('RPMVERIFY_LSTATFAIL')
- #file_results.append(fname)
- return file_results
-
- # 5. Contexts? SELinux stuff?
-
- # Setup what checks to do. This is straight out of the C code.
- if stat.S_ISDIR(lstat.st_mode):
- flags &= DIR_FLAGS
- elif stat.S_ISLNK(lstat.st_mode):
- flags &= LINK_FLAGS
- elif stat.S_ISFIFO(lstat.st_mode):
- flags &= FIFO_FLAGS
- elif stat.S_ISCHR(lstat.st_mode):
- flags &= CHR_FLAGS
- elif stat.S_ISBLK(lstat.st_mode):
- flags &= BLK_FLAGS
- else:
- flags &= REG_FLAGS
-
- if (fflags & rpm.RPMFILE_GHOST):
- flags &= GHOST_FLAGS
-
- flags &= ~(omitmask | RPMVERIFY_FAILURES)
-
- # 8. SELinux stuff.
-
- prelink_size = 0
- if flags & RPMVERIFY_MD5:
- prelink_md5, prelink_size = prelink_md5_check(fname)
- if prelink_md5 == False:
- file_results.append('RPMVERIFY_MD5')
- file_results.append('RPMVERIFY_READFAIL')
- elif prelink_md5 != fmd5:
- file_results.append('RPMVERIFY_MD5')
-
- if flags & RPMVERIFY_LINKTO:
- linkto = os.readlink(fname)
- if not linkto:
- file_results.append('RPMVERIFY_READLINKFAIL')
- file_results.append('RPMVERIFY_LINKTO')
- else:
- if len(rpmlinktos) == 0 or linkto != rpmlinktos:
- file_results.append('RPMVERIFY_LINKTO')
-
- if flags & RPMVERIFY_FILESIZE:
- if not (flags & RPMVERIFY_MD5): # prelink check hasn't been done.
- prelink_size = prelink_size_check(fname)
- if (prelink_size != 0): # This is a prelinked file.
- if (prelink_size != fsize):
- file_results.append('RPMVERIFY_FILESIZE')
- elif lstat.st_size != fsize: # It wasn't a prelinked file.
- file_results.append('RPMVERIFY_FILESIZE')
-
- if flags & RPMVERIFY_MODE:
- metamode = fmode
- filemode = lstat.st_mode
-
- # Comparing the type of %ghost files is meaningless, but perms are ok.
- if fflags & rpm.RPMFILE_GHOST:
- metamode &= ~0xf000
- filemode &= ~0xf000
-
- if (stat.S_IFMT(metamode) != stat.S_IFMT(filemode)) or \
- (stat.S_IMODE(metamode) != stat.S_IMODE(filemode)):
- file_results.append('RPMVERIFY_MODE')
-
- if flags & RPMVERIFY_RDEV:
- if (stat.S_ISCHR(fmode) != stat.S_ISCHR(lstat.st_mode) or
- stat.S_ISBLK(fmode) != stat.S_ISBLK(lstat.st_mode)):
- file_results.append('RPMVERIFY_RDEV')
- elif (s_isdev(fmode) & s_isdev(lstat.st_mode)):
- st_rdev = lstat.st_rdev
- if frdev != st_rdev:
- file_results.append('RPMVERIFY_RDEV')
-
- if flags & RPMVERIFY_MTIME:
- if lstat.st_mtime != fmtime:
- file_results.append('RPMVERIFY_MTIME')
-
- if flags & RPMVERIFY_USER:
- try:
- user = pwd.getpwuid(lstat.st_uid)[0]
- except KeyError:
- user = None
- if not user or not fuser or (user != fuser):
- file_results.append('RPMVERIFY_USER')
-
- if flags & RPMVERIFY_GROUP:
- try:
- group = grp.getgrgid(lstat.st_gid)[0]
- except KeyError:
- group = None
- if not group or not fgroup or (group != fgroup):
- file_results.append('RPMVERIFY_GROUP')
-
- return file_results
-
-def rpm_verify_dependencies(header):
- """
- Check package dependencies. Header is an rpm.hdr.
-
- Don't like opening another ts to do this, but
- it was the only way I could find of clearing the ts
- out.
-
- Have asked on the rpm-maint list on how to do
- this the right way (28 Feb 2007).
-
- ts.check() returns:
-
- ((name, version, release), (reqname, reqversion), \
- flags, suggest, sense)
-
- """
- _ts1 = rpmtransactionset()
- _ts1.addInstall(header, 'Dep Check', 'i')
- dep_errors = _ts1.check()
- _ts1.closeDB()
- return dep_errors
-
-def rpm_verify_package(vp_ts, header, verify_options):
- """
- Verify a single package specified by header. Header is an rpm.hdr.
-
- If errors are found it returns a dictionary of errors.
-
- """
- # Set some transaction level flags.
- vsflags = 0
- if 'nodigest' in verify_options:
- vsflags |= rpm._RPMVSF_NODIGESTS
- if 'nosignature' in verify_options:
- vsflags |= rpm._RPMVSF_NOSIGNATURES
- ovsflags = vp_ts.setVSFlags(vsflags)
-
- # Map from the Python options to the rpm bitwise flags.
- omitmask = 0
-
- if 'nolinkto' in verify_options:
- omitmask |= VERIFY_LINKTO
- if 'nomd5' in verify_options:
- omitmask |= VERIFY_MD5
- if 'nosize' in verify_options:
- omitmask |= VERIFY_SIZE
- if 'nouser' in verify_options:
- omitmask |= VERIFY_USER
- if 'nogroup' in verify_options:
- omitmask |= VERIFY_GROUP
- if 'nomtime' in verify_options:
- omitmask |= VERIFY_MTIME
- if 'nomode' in verify_options:
- omitmask |= VERIFY_MODE
- if 'nordev' in verify_options:
- omitmask |= VERIFY_RDEV
-
- omitmask = ((~omitmask & VERIFY_ATTRS) ^ VERIFY_ATTRS)
-
- package_results = {}
-
- # Check Signatures and Digests.
- # No idea what this might return. Need to break something to see.
- # Setting the vsflags above determines what gets checked in the header.
- hdr_stat = vp_ts.hdrCheck(header.unload())
- if hdr_stat:
- package_results['hdr'] = hdr_stat
-
- # Check Package Depencies.
- if 'nodeps' not in verify_options:
- dep_stat = rpm_verify_dependencies(header)
- if dep_stat:
- package_results['deps'] = dep_stat
-
- # Check all the package files.
- if 'nofiles' not in verify_options:
- vp_fi = header.fiFromHeader()
- for fileinfo in vp_fi:
- # Do not bother doing anything with ghost files.
- # This is what RPM does.
- if fileinfo[4] & rpm.RPMFILE_GHOST:
- continue
-
- # This is only needed because of an inconsistency in the
- # rpm.fi interface.
- linktos = vp_fi.FLink()
-
- file_stat = rpm_verify_file(fileinfo, linktos, omitmask)
-
- #if len(file_stat) > 0 or options.verbose:
- if len(file_stat) > 0:
- fflags = fileinfo[4]
- if fflags & rpm.RPMFILE_CONFIG:
- file_stat.append('c')
- elif fflags & rpm.RPMFILE_DOC:
- file_stat.append('d')
- elif fflags & rpm.RPMFILE_GHOST:
- file_stat.append('g')
- elif fflags & rpm.RPMFILE_LICENSE:
- file_stat.append('l')
- elif fflags & rpm.RPMFILE_PUBKEY:
- file_stat.append('P')
- elif fflags & rpm.RPMFILE_README:
- file_stat.append('r')
- else:
- file_stat.append(' ')
-
- file_stat.append(fileinfo[0]) # The filename.
- package_results.setdefault('files', []).append(file_stat)
-
- # Run the verify script if there is one.
- # Do we want this?
- #if 'noscripts' not in verify_options:
- # script_stat = rpmVerifyscript()
- # if script_stat:
- # package_results['script'] = script_stat
-
- # If there have been any errors, add the package nevra to the result.
- if len(package_results) > 0:
- package_results.setdefault('nevra', (header[rpm.RPMTAG_NAME], \
- header[rpm.RPMTAG_EPOCH], \
- header[rpm.RPMTAG_VERSION], \
- header[rpm.RPMTAG_RELEASE], \
- header[rpm.RPMTAG_ARCH]))
- else:
- package_results = None
-
- # Put things back the way we found them.
- vsflags = vp_ts.setVSFlags(ovsflags)
-
- return package_results
-
-def rpm_verify(verify_ts, verify_pkgspec, verify_options=[]):
- """
- Requires rpmtransactionset() to be run first to get a ts.
-
- pkgspec is a dict specifying the package
- e.g.:
- For a single package
- { name='foo', epoch='20', version='1', release='1', arch='x86_64'}
-
- For all packages
- {}
-
- Or any combination of keywords to select one or more packages to verify.
-
- options is a list of 'rpm --verify' options. Default is to check everything.
- e.g.:
- [ 'nodeps', 'nodigest', 'nofiles', 'noscripts', 'nosignature',
- 'nolinkto' 'nomd5', 'nosize', 'nouser', 'nogroup', 'nomtime',
- 'nomode', 'nordev' ]
-
- Returns a list. One list entry per package. Each list entry is a
- dictionary. Dict keys are 'files', 'deps', 'nevra' and 'hdr'.
- Entries only get added for the failures. If nothing failed, None is
- returned.
-
- Its all a bit messy and probably needs reviewing.
-
- [ { 'hdr': [???],
- 'deps: [((name, version, release), (reqname, reqversion),
- flags, suggest, sense), .... ]
- 'files': [ ['filename1', 'RPMVERIFY_GROUP', 'RPMVERIFY_USER' ],
- ['filename2', 'RPMVERFIY_LSTATFAIL']]
- 'nevra': ['name1', 'epoch1', 'version1', 'release1', 'arch1'] }
- { 'hdr': [???],
- 'deps: [((name, version, release), (reqname, reqversion),
- flags, suggest, sense), .... ]
- 'files': [ ['filename', 'RPMVERIFY_GROUP', 'RPMVERIFY_USER" ],
- ['filename2', 'RPMVERFIY_LSTATFAIL']]
- 'nevra': ['name2', 'epoch2', 'version2', 'release2', 'arch2'] } ]
-
- """
- verify_results = []
- headers = getheadersbykeyword(verify_ts, **verify_pkgspec)
- for header in headers:
- result = rpm_verify_package(verify_ts, header, verify_options)
- if result:
- verify_results.append(result)
-
- return verify_results
-
-def rpmtransactionset():
- """
- A simple wrapper for rpm.TransactionSet() to keep everthiing together.
- Might use it to set some ts level flags later.
-
- """
- ts = rpm.TransactionSet()
- return ts
-
-class Rpmtscallback(object):
- """
- Callback for ts.run(). Used for adding, upgrading and removing packages.
- Starting with all possible reasons codes, but bcfg2 will probably only
- make use of a few of them.
-
- Mostly just printing stuff at the moment to understand how the callback
- is used.
-
- """
- def __init__(self):
- self.fdnos = {}
-
- def callback(self, reason, amount, total, key, client_data):
- """
- Generic rpmts call back.
- """
- if reason == rpm.RPMCALLBACK_INST_OPEN_FILE:
- pass
- elif reason == rpm.RPMCALLBACK_INST_CLOSE_FILE:
- pass
- elif reason == rpm.RPMCALLBACK_INST_START:
- pass
- elif reason == rpm.RPMCALLBACK_TRANS_PROGRESS or \
- reason == rpm.RPMCALLBACK_INST_PROGRESS:
- pass
- # rpm.RPMCALLBACK_INST_PROGRESS'
- elif reason == rpm.RPMCALLBACK_TRANS_START:
- pass
- elif reason == rpm.RPMCALLBACK_TRANS_STOP:
- pass
- elif reason == rpm.RPMCALLBACK_REPACKAGE_START:
- pass
- elif reason == rpm.RPMCALLBACK_REPACKAGE_PROGRESS:
- pass
- elif reason == rpm.RPMCALLBACK_REPACKAGE_STOP:
- pass
- elif reason == rpm.RPMCALLBACK_UNINST_PROGRESS:
- pass
- elif reason == rpm.RPMCALLBACK_UNINST_START:
- pass
- elif reason == rpm.RPMCALLBACK_UNINST_STOP:
- pass
- # How do we get at this?
- # RPM.modified += key
- elif reason == rpm.RPMCALLBACK_UNPACK_ERROR:
- pass
- elif reason == rpm.RPMCALLBACK_CPIO_ERROR:
- pass
- elif reason == rpm.RPMCALLBACK_UNKNOWN:
- pass
- else:
- print('ERROR - Fell through callBack')
-
-
-def rpm_erase(erase_pkgspecs, erase_flags):
- """
- pkgspecs is a list of pkgspec dicts specifying packages
- e.g.:
- For a single package
- { name='foo', epoch='20', version='1', release='1', arch='x86_64'}
-
- """
- erase_ts_flags = 0
- if 'noscripts' in erase_flags:
- erase_ts_flags |= rpm.RPMTRANS_FLAG_NOSCRIPTS
- if 'notriggers' in erase_flags:
- erase_ts_flags |= rpm.RPMTRANS_FLAG_NOTRIGGERS
- if 'repackage' in erase_flags:
- erase_ts_flags |= rpm.RPMTRANS_FLAG_REPACKAGE
-
- erase_ts = rpmtransactionset()
- erase_ts.setFlags(erase_ts_flags)
-
- for pkgspec in erase_pkgspecs:
- idx_list = getindexbykeyword(erase_ts, **pkgspec)
- if len(idx_list) > 1 and not 'allmatches' in erase_flags:
- #pass
- print('ERROR - Multiple package match for erase', pkgspec)
- else:
- for idx in idx_list:
- erase_ts.addErase(idx)
-
- #for te in erase_ts:
-
- erase_problems = []
- if 'nodeps' not in erase_flags:
- erase_problems = erase_ts.check()
-
- if erase_problems == []:
- erase_ts.order()
- erase_callback = Rpmtscallback()
- erase_ts.run(erase_callback.callback, 'Erase')
- #else:
-
- erase_ts.closeDB()
- del erase_ts
- return erase_problems
-
-def display_verify_file(file_results):
- '''
- Display file results similar to rpm --verify.
- '''
- filename = file_results[-1]
- filetype = file_results[-2]
-
- result_string = ''
-
- if 'RPMVERIFY_LSTATFAIL' in file_results:
- result_string = 'missing '
- else:
- if 'RPMVERIFY_FILESIZE' in file_results:
- result_string = result_string + 'S'
- else:
- result_string = result_string + '.'
-
- if 'RPMVERIFY_MODE' in file_results:
- result_string = result_string + 'M'
- else:
- result_string = result_string + '.'
-
- if 'RPMVERIFY_MD5' in file_results:
- if 'RPMVERIFY_READFAIL' in file_results:
- result_string = result_string + '?'
- else:
- result_string = result_string + '5'
- else:
- result_string = result_string + '.'
-
- if 'RPMVERIFY_RDEV' in file_results:
- result_string = result_string + 'D'
- else:
- result_string = result_string + '.'
-
- if 'RPMVERIFY_LINKTO' in file_results:
- if 'RPMVERIFY_READLINKFAIL' in file_results:
- result_string = result_string + '?'
- else:
- result_string = result_string + 'L'
- else:
- result_string = result_string + '.'
-
- if 'RPMVERIFY_USER' in file_results:
- result_string = result_string + 'U'
- else:
- result_string = result_string + '.'
-
- if 'RPMVERIFY_GROUP' in file_results:
- result_string = result_string + 'G'
- else:
- result_string = result_string + '.'
-
- if 'RPMVERIFY_MTIME' in file_results:
- result_string = result_string + 'T'
- else:
- result_string = result_string + '.'
-
- print(result_string + ' ' + filetype + ' ' + filename)
- sys.stdout.flush()
-
-#===============================================================================
-# Some options and output to assist with development and testing.
-# These are not intended for normal use.
-if __name__ == "__main__":
-
- p = optparse.OptionParser()
-
- p.add_option('--name', action='store', \
- default=None, \
- help='''Package name to verify.
-
- ******************************************
- NOT SPECIFYING A NAME MEANS 'ALL' PACKAGES.
- ******************************************
-
- The specified operation will be carried out on all
- instances of packages that match the package specification
- (name, epoch, version, release, arch).''')
-
- p.add_option('--epoch', action='store', \
- default=None, \
- help='''Package epoch.''')
-
- p.add_option('--version', action='store', \
- default=None, \
- help='''Package version.''')
-
- p.add_option('--release', action='store', \
- default=None, \
- help='''Package release.''')
-
- p.add_option('--arch', action='store', \
- default=None, \
- help='''Package arch.''')
-
- p.add_option('--erase', '-e', action='store_true', \
- default=None, \
- help='''****************************************************
- REMOVE PACKAGES. THERE ARE NO WARNINGS. MULTIPLE
- PACKAGES WILL BE REMOVED IF A FULL PACKAGE SPEC IS NOT
- GIVEN. E.G. IF JUST A NAME IS GIVEN ALL INSTALLED
- INSTANCES OF THAT PACKAGE WILL BE REMOVED PROVIDED
- DEPENDENCY CHECKS PASS. IF JUST AN EPOCH IS GIVEN
- ALL PACKAGE INSTANCES WITH THAT EPOCH WILL BE REMOVED.
- ****************************************************''')
-
- p.add_option('--list', '-l', action='store_true', \
- help='''List package identity info. rpm -qa ish equivalent
- intended for use in RefreshPackages().''')
-
- p.add_option('--verify', action='store_true', \
- help='''Verify Package(s). Output is only produced after all
- packages has been verified. Be patient.''')
-
- p.add_option('--verbose', '-v', action='store_true', \
- help='''Verbose output for --verify option. Output is the
- same as rpm -v --verify.''')
-
- p.add_option('--nodeps', action='store_true', \
- default=False, \
- help='Do not do dependency testing.')
-
- p.add_option('--nodigest', action='store_true', \
- help='Do not check package digests.')
-
- p.add_option('--nofiles', action='store_true', \
- help='Do not do file checks.')
-
- p.add_option('--noscripts', action='store_true', \
- help='Do not run verification scripts.')
-
- p.add_option('--nosignature', action='store_true', \
- help='Do not do package signature verification.')
-
- p.add_option('--nolinkto', action='store_true', \
- help='Do not do symlink tests.')
-
- p.add_option('--nomd5', action='store_true', \
- help='''Do not do MD5 checksums on files. Note that this does
- not work for prelink files yet.''')
-
- p.add_option('--nosize', action='store_true', \
- help='''Do not do file size tests. Note that this does not work
- for prelink files yet.''')
-
- p.add_option('--nouser', action='store_true', \
- help='Do not check file user ownership.')
-
- p.add_option('--nogroup', action='store_true', \
- help='Do not check file group ownership.')
-
- p.add_option('--nomtime', action='store_true', \
- help='Do not check file modification times.')
-
- p.add_option('--nomode', action='store_true', \
- help='Do not check file modes (permissions).')
-
- p.add_option('--nordev', action='store_true', \
- help='Do not check device node.')
-
- p.add_option('--notriggers', action='store_true', \
- help='Do not do not generate triggers on erase.')
-
- p.add_option('--repackage', action='store_true', \
- help='''Do repackage on erase.i Packages are put
- in /var/spool/repackage.''')
-
- p.add_option('--allmatches', action='store_true', \
- help='''Remove all package instances that match the
- pkgspec.
-
- ***************************************************
- NO WARNINGS ARE GIVEN. IF THERE IS NO PACKAGE SPEC
- THAT MEANS ALL PACKAGES!!!!
- ***************************************************''')
-
- options, arguments = p.parse_args()
-
- pkgspec = {}
- rpm_options = []
-
- if options.nodeps:
- rpm_options.append('nodeps')
-
- if options.nodigest:
- rpm_options.append('nodigest')
-
- if options.nofiles:
- rpm_options.append('nofiles')
-
- if options.noscripts:
- rpm_options.append('noscripts')
-
- if options.nosignature:
- rpm_options.append('nosignature')
-
- if options.nolinkto:
- rpm_options.append('nolinkto')
-
- if options.nomd5:
- rpm_options.append('nomd5')
-
- if options.nosize:
- rpm_options.append('nosize')
-
- if options.nouser:
- rpm_options.append('nouser')
-
- if options.nogroup:
- rpm_options.append('nogroup')
-
- if options.nomtime:
- rpm_options.append('nomtime')
-
- if options.nomode:
- rpm_options.append('nomode')
-
- if options.nordev:
- rpm_options.append('nordev')
-
- if options.repackage:
- rpm_options.append('repackage')
-
- if options.allmatches:
- rpm_options.append('allmatches')
-
- main_ts = rpmtransactionset()
-
- cmdline_pkgspec = {}
- if options.name != 'all':
- if options.name:
- cmdline_pkgspec['name'] = str(options.name)
- if options.epoch:
- cmdline_pkgspec['epoch'] = str(options.epoch)
- if options.version:
- cmdline_pkgspec['version'] = str(options.version)
- if options.release:
- cmdline_pkgspec['release'] = str(options.release)
- if options.arch:
- cmdline_pkgspec['arch'] = str(options.arch)
-
- if options.verify:
- results = rpm_verify(main_ts, cmdline_pkgspec, rpm_options)
- for r in results:
- files = r.get('files', '')
- for f in files:
- display_verify_file(f)
-
- elif options.list:
- for p in rpmpackagelist(main_ts):
- print(p)
-
- elif options.erase:
- if options.name:
- rpm_erase([cmdline_pkgspec], rpm_options)
- else:
- print('You must specify the "--name" option')