Blame SOURCES/BZ-1335250-fssnapshot-handle-lvm-errors.patch

eb5f31
diff -up yum-3.4.3/yumcommands.py.orig yum-3.4.3/yumcommands.py
eb5f31
--- yum-3.4.3/yumcommands.py.orig	2016-07-21 11:39:40.422379800 +0200
eb5f31
+++ yum-3.4.3/yumcommands.py	2016-07-21 11:40:42.144992126 +0200
eb5f31
@@ -42,6 +42,7 @@ import errno
eb5f31
 import yum.config
eb5f31
 from yum import updateinfo
eb5f31
 from yum.packages import parsePackages
eb5f31
+from yum.fssnapshots import LibLVMError, lvmerr2str
eb5f31
 
eb5f31
 def _err_mini_usage(base, basecmd):
eb5f31
     if basecmd not in base.yum_cli_commands:
eb5f31
@@ -4266,12 +4267,19 @@ class FSSnapshotCommand(YumCommand):
eb5f31
             return 1, [basecmd + ' ' + subcommand + ' done']
eb5f31
 
eb5f31
         if subcommand == 'list':
eb5f31
-            snaps = base.fssnap.old_snapshots()
eb5f31
+            try:
eb5f31
+                snaps = base.fssnap.old_snapshots()
eb5f31
+            except LibLVMError as e:
eb5f31
+                return 1, [_("Failed to list snapshots: ") + lvmerr2str(e)]
eb5f31
             print _("List of %u snapshosts:") % len(snaps)
eb5f31
             self._li_snaps(base, snaps)
eb5f31
 
eb5f31
         if subcommand == 'delete':
eb5f31
-            snaps = base.fssnap.old_snapshots()
eb5f31
+            msg = _("Failed to delete snapshots: ")
eb5f31
+            try:
eb5f31
+                snaps = base.fssnap.old_snapshots()
eb5f31
+            except LibLVMError as e:
eb5f31
+                return 1, [msg + lvmerr2str(e)]
eb5f31
             devs = [x['dev'] for x in snaps]
eb5f31
             snaps = set()
eb5f31
             for dev in devs:
eb5f31
@@ -4282,13 +4290,20 @@ class FSSnapshotCommand(YumCommand):
eb5f31
                     if dev == extcmd or fnmatch.fnmatch(dev, extcmd):
eb5f31
                         snaps.add(dev)
eb5f31
                         break
eb5f31
-            snaps = base.fssnap.del_snapshots(devices=snaps)
eb5f31
+            try:
eb5f31
+                snaps = base.fssnap.del_snapshots(devices=snaps)
eb5f31
+            except LibLVMError as e:
eb5f31
+                return 1, [msg + lvmerr2str(e)]
eb5f31
             print _("Deleted %u snapshosts:") % len(snaps)
eb5f31
             self._li_snaps(base, snaps)
eb5f31
 
eb5f31
         if subcommand in ('have-space', 'has-space'):
eb5f31
             pc = base.conf.fssnap_percentage
eb5f31
-            if base.fssnap.has_space(pc):
eb5f31
+            try:
eb5f31
+                has_space = base.fssnap.has_space(pc)
eb5f31
+            except LibLVMError as e:
eb5f31
+                return 1, [_("Could not determine free space on logical volumes: ") + lvmerr2str(e)]
eb5f31
+            if has_space:
eb5f31
                 print _("Space available to take a snapshot.")
eb5f31
             else:
eb5f31
                 print _("Not enough space available on logical volumes to take a snapshot.")
eb5f31
@@ -4296,14 +4311,22 @@ class FSSnapshotCommand(YumCommand):
eb5f31
         if subcommand == 'create':
eb5f31
             tags = {'*': ['reason=manual']}
eb5f31
             pc = base.conf.fssnap_percentage
eb5f31
-            snaps = base.fssnap.snapshot(pc, tags=tags)
eb5f31
+            msg = _("Failed to create snapshots")
eb5f31
+            try:
eb5f31
+                snaps = base.fssnap.snapshot(pc, tags=tags)
eb5f31
+            except LibLVMError as e:
eb5f31
+                msg += ": " + lvmerr2str(e)
eb5f31
+                snaps = []
eb5f31
             if not snaps:
eb5f31
-                print _("Failed to create snapshots")
eb5f31
+                print msg
eb5f31
             for (odev, ndev) in snaps:
eb5f31
                 print _("Created snapshot from %s, results is: %s") %(odev,ndev)
eb5f31
 
eb5f31
         if subcommand == 'summary':
eb5f31
-            snaps = base.fssnap.old_snapshots()
eb5f31
+            try:
eb5f31
+                snaps = base.fssnap.old_snapshots()
eb5f31
+            except LibLVMError as e:
eb5f31
+                return 1, [_("Failed to list snapshots: ") + lvmerr2str(e)]
eb5f31
             if not snaps:
eb5f31
                 print _("No snapshots, LVM version:"), base.fssnap.version
eb5f31
                 return 0, [basecmd + ' ' + subcommand + ' done']
eb5f31
diff -up yum-3.4.3/yum/fssnapshots.py.orig yum-3.4.3/yum/fssnapshots.py
eb5f31
--- yum-3.4.3/yum/fssnapshots.py.orig	2016-07-21 11:39:40.351380246 +0200
eb5f31
+++ yum-3.4.3/yum/fssnapshots.py	2016-07-21 11:40:02.211242946 +0200
eb5f31
@@ -6,6 +6,7 @@ import time
eb5f31
 from datetime import datetime
eb5f31
 
eb5f31
 import subprocess
eb5f31
+from yum import _
eb5f31
 
eb5f31
 try:
eb5f31
     import lvm
eb5f31
@@ -24,6 +25,14 @@ except:
eb5f31
     lvm = None
eb5f31
     _ver = None
eb5f31
 
eb5f31
+if lvm is not None:
eb5f31
+    from lvm import LibLVMError
eb5f31
+    class _ResultError(LibLVMError):
eb5f31
+        """Exception raised for LVM calls resulting in bad return values."""
eb5f31
+        pass
eb5f31
+else:
eb5f31
+    LibLVMError = None
eb5f31
+
eb5f31
 
eb5f31
 def _is_origin(lv):
eb5f31
     snap = lv.getAttr()
eb5f31
@@ -53,14 +62,18 @@ def _vg_name2lv(vg, lvname):
eb5f31
         return None
eb5f31
 
eb5f31
 def _list_vg_names():
eb5f31
-    names = lvm.listVgNames()
eb5f31
+    try:
eb5f31
+        names = lvm.listVgNames()
eb5f31
+    except LibLVMError:
eb5f31
+        # Try to use the lvm binary instead
eb5f31
+        names = []
eb5f31
 
eb5f31
     if not names: # Could be just broken...
eb5f31
         p = subprocess.Popen(["/sbin/lvm", "vgs", "-o", "vg_name"],
eb5f31
                              stdout=subprocess.PIPE, stderr=subprocess.PIPE)
eb5f31
         err = p.wait()
eb5f31
         if err:
eb5f31
-            return [] # Meh.
eb5f31
+            raise _ResultError(_("Failed to obtain volume group names"))
eb5f31
 
eb5f31
         output = p.communicate()[0]
eb5f31
         output = output.split('\n')
eb5f31
@@ -132,6 +145,25 @@ def _lv_data(vg, lv):
eb5f31
 
eb5f31
     return data
eb5f31
 
eb5f31
+def _log_traceback(func):
eb5f31
+    """Decorator for _FSSnap methods that logs LVM tracebacks."""
eb5f31
+    def wrap(self, *args, **kwargs):
eb5f31
+        try:
eb5f31
+            return func(self, *args, **kwargs)
eb5f31
+        except LibLVMError as e:
eb5f31
+            if self._logger is not None:
eb5f31
+                self._logger.exception(e)
eb5f31
+            raise
eb5f31
+    return wrap
eb5f31
+
eb5f31
+def lvmerr2str(exc):
eb5f31
+    """Convert a LibLVMError instance to a readable error message."""
eb5f31
+    if type(exc) == LibLVMError and len(exc.args) == 2:
eb5f31
+        # args[0] is the error number so ignore that
eb5f31
+        return exc.args[1]
eb5f31
+    else:
eb5f31
+        return str(exc)
eb5f31
+
eb5f31
 
eb5f31
 class _FSSnap(object):
eb5f31
 
eb5f31
@@ -139,7 +171,7 @@ class _FSSnap(object):
eb5f31
     # New style is: fedora/root fedora/swap
eb5f31
     # New style is: redhat/root redhat/swap
eb5f31
     def __init__(self, root="/", lookup_mounts=True,
eb5f31
-                 devices=('!*/swap', '!*/lv_swap')):
eb5f31
+                 devices=('!*/swap', '!*/lv_swap'), logger=None):
eb5f31
         if not lvm or os.geteuid():
eb5f31
             devices = []
eb5f31
 
eb5f31
@@ -150,12 +182,18 @@ class _FSSnap(object):
eb5f31
         self._postfix = None
eb5f31
         self._root = root
eb5f31
         self._devs = devices
eb5f31
-        self._vgnames = []
eb5f31
+        self._vgname_list = None
eb5f31
+        # Logger object to be used for LVM traceback logging
eb5f31
+        self._logger = logger
eb5f31
 
eb5f31
         if not self._devs:
eb5f31
             return
eb5f31
 
eb5f31
-        self._vgnames = _list_vg_names() if self.available else []
eb5f31
+    @property
eb5f31
+    def _vgnames(self):
eb5f31
+        if self._vgname_list is None:
eb5f31
+            self._vgname_list = _list_vg_names() if self.available else []
eb5f31
+        return self._vgname_list
eb5f31
 
eb5f31
     def _use_dev(self, vgname, lv=None):
eb5f31
 
eb5f31
@@ -196,6 +234,7 @@ class _FSSnap(object):
eb5f31
 
eb5f31
         return found_neg
eb5f31
 
eb5f31
+    @_log_traceback
eb5f31
     def has_space(self, percentage=100):
eb5f31
         """ See if we have enough space to try a snapshot. """
eb5f31
 
eb5f31
@@ -207,7 +246,8 @@ class _FSSnap(object):
eb5f31
 
eb5f31
             vg = lvm.vgOpen(vgname, 'r')
eb5f31
             if not vg:
eb5f31
-                return False
eb5f31
+                raise _ResultError(
eb5f31
+                    _("Unknown error when opening volume group ") + vgname)
eb5f31
 
eb5f31
             vgfsize = vg.getFreeSize()
eb5f31
             lvssize = 0
eb5f31
@@ -230,6 +270,7 @@ class _FSSnap(object):
eb5f31
         return ret
eb5f31
 
eb5f31
 
eb5f31
+    @_log_traceback
eb5f31
     def snapshot(self, percentage=100, prefix='', postfix=None, tags={}):
eb5f31
         """ Attempt to take a snapshot, note that errors can happen after
eb5f31
             this function succeeds. """
eb5f31
@@ -245,7 +286,8 @@ class _FSSnap(object):
eb5f31
 
eb5f31
             vg = lvm.vgOpen(vgname, 'w')
eb5f31
             if not vg:
eb5f31
-                return False
eb5f31
+                raise _ResultError(
eb5f31
+                    _("Unknown error when opening volume group ") + vgname)
eb5f31
 
eb5f31
             for lv in vg.listLVs():
eb5f31
                 lvname = lv.getName()
eb5f31
@@ -257,7 +299,8 @@ class _FSSnap(object):
eb5f31
                 nlv = lv.snapshot(nlvname, (lv.getSize() * percentage) / 100)
eb5f31
                 if not nlv: # Failed here ... continuing seems bad.
eb5f31
                     vg.close()
eb5f31
-                    return None
eb5f31
+                    raise _ResultError(
eb5f31
+                        _("Unknown error when creating snapshot ") + nlvname)
eb5f31
 
eb5f31
                 odev = "%s/%s" % (vgname,  lvname)
eb5f31
                 ndev = "%s/%s" % (vgname, nlvname)
eb5f31
@@ -280,6 +323,7 @@ class _FSSnap(object):
eb5f31
 
eb5f31
         return ret
eb5f31
 
eb5f31
+    @_log_traceback
eb5f31
     def old_snapshots(self):
eb5f31
         """ List data for old snapshots. """
eb5f31
 
eb5f31
@@ -289,6 +333,9 @@ class _FSSnap(object):
eb5f31
             # see stuff after changing config. options.
eb5f31
 
eb5f31
             vg = lvm.vgOpen(vgname, 'w')
eb5f31
+            if not vg:
eb5f31
+                raise _ResultError(
eb5f31
+                    _("Unknown error when opening volume group ") + vgname)
eb5f31
 
eb5f31
             for lv in vg.listLVs():
eb5f31
 
eb5f31
@@ -300,6 +347,7 @@ class _FSSnap(object):
eb5f31
 
eb5f31
         return ret
eb5f31
 
eb5f31
+    @_log_traceback
eb5f31
     def del_snapshots(self, devices=[]):
eb5f31
         """ Remove snapshots. """
eb5f31
 
eb5f31
@@ -318,6 +366,9 @@ class _FSSnap(object):
eb5f31
 
eb5f31
         for vgname in togo:
eb5f31
             vg = lvm.vgOpen(vgname, 'w')
eb5f31
+            if not vg:
eb5f31
+                raise _ResultError(
eb5f31
+                    _("Unknown error when opening volume group ") + vgname)
eb5f31
 
eb5f31
             for lvname in togo[vgname]:
eb5f31
                 lv = _vg_name2lv(vg, lvname)
eb5f31
diff -up yum-3.4.3/yum/__init__.py.orig yum-3.4.3/yum/__init__.py
eb5f31
--- yum-3.4.3/yum/__init__.py.orig	2016-07-21 11:39:40.425379782 +0200
eb5f31
+++ yum-3.4.3/yum/__init__.py	2016-07-21 11:40:02.211242946 +0200
eb5f31
@@ -81,6 +81,7 @@ import yumRepo
eb5f31
 import callbacks
eb5f31
 import yum.history
eb5f31
 import yum.fssnapshots
eb5f31
+from yum.fssnapshots import LibLVMError, lvmerr2str
eb5f31
 import yum.igroups
eb5f31
 import update_md
eb5f31
 
eb5f31
@@ -204,6 +205,7 @@ class YumBase(depsolve.Depsolve):
eb5f31
         self._not_found_i = {}
eb5f31
         self.logger = logging.getLogger("yum.YumBase")
eb5f31
         self.verbose_logger = logging.getLogger("yum.verbose.YumBase")
eb5f31
+        self.file_logger = logging.getLogger("yum.filelogging.YumBase")
eb5f31
         self._override_sigchecks = False
eb5f31
         self._repos = RepoStorage(self)
eb5f31
         self.repo_setopts = {} # since we have to use repo_setopts in base and 
eb5f31
@@ -1048,7 +1050,8 @@ class YumBase(depsolve.Depsolve):
eb5f31
         if self._fssnap is None:
eb5f31
             devices = self.conf.fssnap_devices
eb5f31
             self._fssnap = yum.fssnapshots._FSSnap(root=self.conf.installroot,
eb5f31
-                                                   devices=devices)
eb5f31
+                                                   devices=devices,
eb5f31
+                                                   logger=self.file_logger)
eb5f31
 
eb5f31
         return self._fssnap
eb5f31
 
eb5f31
@@ -1726,6 +1729,37 @@ much more problems).
eb5f31
         :raises: :class:`yum.Errors.YumRPMTransError` if there is a
eb5f31
            transaction cannot be completed
eb5f31
         """
eb5f31
+
eb5f31
+        def create_snapshot(post=False):
eb5f31
+            """Create the pre or post trans snapshot if we have free space."""
eb5f31
+            msg = _("Not enough space on logical volumes to create %s FS snapshot." %
eb5f31
+                    ("post trans" if post else "pre."))
eb5f31
+            try:
eb5f31
+                has_space = self.fssnap.has_space(self.conf.fssnap_percentage)
eb5f31
+            except LibLVMError as e:
eb5f31
+                msg = _("Could not determine free space on logical volumes: ") + lvmerr2str(e)
eb5f31
+                has_space = False
eb5f31
+            if not has_space:
eb5f31
+                if not post and self.conf.fssnap_abort_on_errors in ('snapshot-failure', 'any'):
eb5f31
+                    raise Errors.YumRPMTransError(msg="Aborting transaction", errors=msg)
eb5f31
+                else:
eb5f31
+                    self.verbose_logger.critical(msg)
eb5f31
+            else:
eb5f31
+                tags = {'*': ['reason=automatic']} # FIXME: pre. and post tags
eb5f31
+                msg = _("Failed to create snapshot")
eb5f31
+                try:
eb5f31
+                    snaps = self.fssnap.snapshot(self.conf.fssnap_percentage, tags=tags)
eb5f31
+                except LibLVMError as e:
eb5f31
+                    msg += ": " + lvmerr2str(e)
eb5f31
+                    snaps = []
eb5f31
+                if not snaps:
eb5f31
+                    if not post and self.conf.fssnap_abort_on_errors in ('snapshot-failure', 'any'):
eb5f31
+                        raise Errors.YumRPMTransError(msg="Aborting transaction", errors=msg)
eb5f31
+                    else:
eb5f31
+                        self.verbose_logger.critical(msg)
eb5f31
+                for (odev, ndev) in snaps:
eb5f31
+                    self.verbose_logger.info(_("Created snapshot from %s, results is: %s") % (odev, ndev))
eb5f31
+
eb5f31
         if (self.conf.fssnap_automatic_pre or self.conf.fssnap_automatic_post) and not self.fssnap.available:
eb5f31
             msg = _("Snapshot support not available.")
eb5f31
             if self.conf.fssnap_abort_on_errors in ('broken-setup', 'any'):
eb5f31
@@ -1737,7 +1771,13 @@ much more problems).
eb5f31
                                        self.conf.fssnap_automatic_post) and
eb5f31
                                       self.conf.fssnap_automatic_keep):
eb5f31
             # Automatically kill old snapshots...
eb5f31
-            snaps = self.fssnap.old_snapshots()
eb5f31
+            cleanup_fail = False
eb5f31
+            try:
eb5f31
+                snaps = self.fssnap.old_snapshots()
eb5f31
+            except LibLVMError as e:
eb5f31
+                self.verbose_logger.debug(lvmerr2str(e))
eb5f31
+                cleanup_fail = True
eb5f31
+                snaps = []
eb5f31
             snaps = sorted(snaps, key=lambda x: (x['ctime'], x['origin_dev']),
eb5f31
                            reverse=True)
eb5f31
             last = '<n/a>'
eb5f31
@@ -1754,30 +1794,22 @@ much more problems).
eb5f31
                 if num > self.conf.fssnap_automatic_keep:
eb5f31
                     todel.append(snap['dev'])
eb5f31
             # Display something to the user?
eb5f31
-            snaps = self.fssnap.del_snapshots(devices=todel)
eb5f31
+            try:
eb5f31
+                snaps = self.fssnap.del_snapshots(devices=todel)
eb5f31
+            except LibLVMError as e:
eb5f31
+                self.verbose_logger.debug(lvmerr2str(e))
eb5f31
+                cleanup_fail = True
eb5f31
+                snaps = []
eb5f31
             if len(snaps):
eb5f31
                 self.verbose_logger.info(_("Deleted %u snapshots.") % len(snaps))
eb5f31
+            elif cleanup_fail:
eb5f31
+                self.verbose_logger.warning(_("Skipping the cleanup of old "
eb5f31
+                                              "snapshots due to errors"))
eb5f31
 
eb5f31
         if (self.fssnap.available and
eb5f31
             (not self.ts.isTsFlagSet(rpm.RPMTRANS_FLAG_TEST) and
eb5f31
             self.conf.fssnap_automatic_pre)):
eb5f31
-            if not self.fssnap.has_space(self.conf.fssnap_percentage):
eb5f31
-                msg = _("Not enough space on logical volumes to create pre. FS snapshot.")
eb5f31
-                if self.conf.fssnap_abort_on_errors in ('snapshot-failure', 'any'):
eb5f31
-                    raise Errors.YumRPMTransError(msg="Aborting transaction", errors=msg)
eb5f31
-                else:
eb5f31
-                    self.verbose_logger.critical(msg)
eb5f31
-            else:
eb5f31
-                tags = {'*': ['reason=automatic']} # FIXME: pre. tags
eb5f31
-                snaps = self.fssnap.snapshot(self.conf.fssnap_percentage, tags=tags)
eb5f31
-                if not snaps:
eb5f31
-                    msg = _("Failed to create snapshot")
eb5f31
-                    if self.conf.fssnap_abort_on_errors in ('snapshot-failure', 'any'):
eb5f31
-                        raise Errors.YumRPMTransError(msg="Aborting transaction", errors=msg)
eb5f31
-                    else:
eb5f31
-                        self.verbose_logger.critical(msg)
eb5f31
-                for (odev, ndev) in snaps:
eb5f31
-                    self.verbose_logger.info(_("Created snapshot from %s, results is: %s") % (odev, ndev))
eb5f31
+            create_snapshot()
eb5f31
 
eb5f31
         self.plugins.run('pretrans')
eb5f31
 
eb5f31
@@ -1912,16 +1944,7 @@ much more problems).
eb5f31
         if (self.fssnap.available and
eb5f31
             (not self.ts.isTsFlagSet(rpm.RPMTRANS_FLAG_TEST) and
eb5f31
             self.conf.fssnap_automatic_post)):
eb5f31
-            if not self.fssnap.has_space(self.conf.fssnap_percentage):
eb5f31
-                msg = _("Not enough space on logical volumes to create post trans FS snapshot.")
eb5f31
-                self.verbose_logger.critical(msg)
eb5f31
-            else:
eb5f31
-                tags = {'*': ['reason=automatic']} # FIXME: post tags
eb5f31
-                snaps = self.fssnap.snapshot(self.conf.fssnap_percentage, tags=tags)
eb5f31
-                if not snaps:
eb5f31
-                    self.verbose_logger.critical(_("Failed to create snapshot"))
eb5f31
-                for (odev, ndev) in snaps:
eb5f31
-                    self.verbose_logger.info(_("Created snapshot from %s, results is: %s") % (odev, ndev))
eb5f31
+            create_snapshot(post=True)
eb5f31
         return resultobject
eb5f31
 
eb5f31
     def verifyTransaction(self, resultobject=None, txmbr_cb=None):