591b7e
From e78ae6d16009263a8dfcd91ea8ce8fc08a077529 Mon Sep 17 00:00:00 2001
591b7e
From: Eduardo Otubo <otubo@redhat.com>
591b7e
Date: Tue, 28 Apr 2020 08:22:03 +0200
591b7e
Subject: [PATCH 1/3] Do not use fallocate in swap file creation on xfs. (#70)
591b7e
591b7e
RH-Author: Eduardo Otubo <otubo@redhat.com>
591b7e
Message-id: <20200422130428.7663-2-otubo@redhat.com>
591b7e
Patchwork-id: 96031
591b7e
O-Subject: [RHEL-7.7.z/RHEL-7.8.z cloud-init PATCH 1/3] Do not use fallocate in swap file creation on xfs. (#70)
591b7e
Bugzilla: 1801094
591b7e
RH-Acked-by: Vitaly Kuznetsov <vkuznets@redhat.com>
591b7e
RH-Acked-by: Cathy Avery <cavery@redhat.com>
591b7e
591b7e
commit 6603706eec1c39d9d591c8ffa0ef7171b74d84d6
591b7e
Author: Eduardo Otubo <otubo@redhat.com>
591b7e
Date:   Thu Jan 23 17:41:48 2020 +0100
591b7e
591b7e
    Do not use fallocate in swap file creation on xfs. (#70)
591b7e
591b7e
    When creating a swap file on an xfs filesystem, fallocate cannot be used.
591b7e
    Doing so results in failure of swapon and a message like:
591b7e
     swapon: swapfile has holes
591b7e
591b7e
    The solution here is to maintain a list (currently containing only XFS)
591b7e
    of filesystems where fallocate cannot be used. The, on those fileystems
591b7e
    use the slower but functional 'dd' method.
591b7e
591b7e
    Signed-off-by: Eduardo Otubo <otubo@redhat.com>
591b7e
    Co-authored-by: Adam Dobrawy <naczelnik@jawnosc.tk>
591b7e
    Co-authored-by:  Scott Moser <smoser@brickies.net>
591b7e
    Co-authored-by: Daniel Watkins <daniel@daniel-watkins.co.uk>
591b7e
591b7e
    LP: #1781781
591b7e
591b7e
Signed-off-bt: Eduardo Otubo <otubo@redhat.com>
591b7e
Signed-off-by: Miroslav Rezanina <mrezanin@redhat.com>
591b7e
---
591b7e
 cloudinit/config/cc_mounts.py                      | 67 ++++++++++++++++------
591b7e
 .../unittests/test_handler/test_handler_mounts.py  | 12 ++++
591b7e
 2 files changed, 62 insertions(+), 17 deletions(-)
591b7e
591b7e
diff --git a/cloudinit/config/cc_mounts.py b/cloudinit/config/cc_mounts.py
591b7e
index 123ffb8..6884ddf 100644
591b7e
--- a/cloudinit/config/cc_mounts.py
591b7e
+++ b/cloudinit/config/cc_mounts.py
591b7e
@@ -223,13 +223,58 @@ def suggested_swapsize(memsize=None, maxsize=None, fsys=None):
591b7e
     return size
591b7e
 
591b7e
 
591b7e
+def create_swapfile(fname, size):
591b7e
+    """Size is in MiB."""
591b7e
+
591b7e
+    errmsg = "Failed to create swapfile '%s' of size %dMB via %s: %s"
591b7e
+
591b7e
+    def create_swap(fname, size, method):
591b7e
+        LOG.debug("Creating swapfile in '%s' on fstype '%s' using '%s'",
591b7e
+                  fname, fstype, method)
591b7e
+
591b7e
+        if method == "fallocate":
591b7e
+            cmd = ['fallocate', '-l', '%dM' % size, fname]
591b7e
+        elif method == "dd":
591b7e
+            cmd = ['dd', 'if=/dev/zero', 'of=%s' % fname, 'bs=1M',
591b7e
+                   'count=%d' % size]
591b7e
+
591b7e
+        try:
591b7e
+            util.subp(cmd, capture=True)
591b7e
+        except util.ProcessExecutionError as e:
591b7e
+            LOG.warning(errmsg, fname, size, method, e)
591b7e
+            util.del_file(fname)
591b7e
+
591b7e
+    swap_dir = os.path.dirname(fname)
591b7e
+    util.ensure_dir(swap_dir)
591b7e
+
591b7e
+    fstype = util.get_mount_info(swap_dir)[1]
591b7e
+
591b7e
+    if fstype in ("xfs", "btrfs"):
591b7e
+        create_swap(fname, size, "dd")
591b7e
+    else:
591b7e
+        try:
591b7e
+            create_swap(fname, size, "fallocate")
591b7e
+        except util.ProcessExecutionError as e:
591b7e
+            LOG.warning(errmsg, fname, size, "dd", e)
591b7e
+            LOG.warning("Will attempt with dd.")
591b7e
+            create_swap(fname, size, "dd")
591b7e
+
591b7e
+    util.chmod(fname, 0o600)
591b7e
+    try:
591b7e
+        util.subp(['mkswap', fname])
591b7e
+    except util.ProcessExecutionError:
591b7e
+        util.del_file(fname)
591b7e
+        raise
591b7e
+
591b7e
+
591b7e
 def setup_swapfile(fname, size=None, maxsize=None):
591b7e
     """
591b7e
     fname: full path string of filename to setup
591b7e
     size: the size to create. set to "auto" for recommended
591b7e
     maxsize: the maximum size
591b7e
     """
591b7e
-    tdir = os.path.dirname(fname)
591b7e
+    swap_dir = os.path.dirname(fname)
591b7e
+    mibsize = str(int(size / (2 ** 20)))
591b7e
     if str(size).lower() == "auto":
591b7e
         try:
591b7e
             memsize = util.read_meminfo()['total']
591b7e
@@ -237,28 +282,16 @@ def setup_swapfile(fname, size=None, maxsize=None):
591b7e
             LOG.debug("Not creating swap: failed to read meminfo")
591b7e
             return
591b7e
 
591b7e
-        util.ensure_dir(tdir)
591b7e
-        size = suggested_swapsize(fsys=tdir, maxsize=maxsize,
591b7e
+        util.ensure_dir(swap_dir)
591b7e
+        size = suggested_swapsize(fsys=swap_dir, maxsize=maxsize,
591b7e
                                   memsize=memsize)
591b7e
 
591b7e
     if not size:
591b7e
         LOG.debug("Not creating swap: suggested size was 0")
591b7e
         return
591b7e
 
591b7e
-    mbsize = str(int(size / (2 ** 20)))
591b7e
-    msg = "creating swap file '%s' of %sMB" % (fname, mbsize)
591b7e
-    try:
591b7e
-        util.ensure_dir(tdir)
591b7e
-        util.log_time(LOG.debug, msg, func=util.subp,
591b7e
-                      args=[['sh', '-c',
591b7e
-                            ('rm -f "$1" && umask 0066 && '
591b7e
-                             '{ fallocate -l "${2}M" "$1" || '
591b7e
-                             ' dd if=/dev/zero "of=$1" bs=1M "count=$2"; } && '
591b7e
-                             'mkswap "$1" || { r=$?; rm -f "$1"; exit $r; }'),
591b7e
-                             'setup_swap', fname, mbsize]])
591b7e
-
591b7e
-    except Exception as e:
591b7e
-        raise IOError("Failed %s: %s" % (msg, e))
591b7e
+    util.log_time(LOG.debug, msg="Setting up swap file", func=create_swapfile,
591b7e
+                  args=[fname, mibsize])
591b7e
 
591b7e
     return fname
591b7e
 
591b7e
diff --git a/tests/unittests/test_handler/test_handler_mounts.py b/tests/unittests/test_handler/test_handler_mounts.py
591b7e
index 0fb160b..7bcefa0 100644
591b7e
--- a/tests/unittests/test_handler/test_handler_mounts.py
591b7e
+++ b/tests/unittests/test_handler/test_handler_mounts.py
591b7e
@@ -181,6 +181,18 @@ class TestFstabHandling(test_helpers.FilesystemMockingTestCase):
591b7e
 
591b7e
         return dev
591b7e
 
591b7e
+    def test_swap_integrity(self):
591b7e
+        '''Ensure that the swap file is correctly created and can
591b7e
+        swapon successfully. Fixing the corner case of:
591b7e
+        kernel: swapon: swapfile has holes'''
591b7e
+
591b7e
+        fstab = '/swap.img swap swap defaults 0 0\n'
591b7e
+
591b7e
+        with open(cc_mounts.FSTAB_PATH, 'w') as fd:
591b7e
+            fd.write(fstab)
591b7e
+        cc = {'swap': ['filename: /swap.img', 'size: 512', 'maxsize: 512']}
591b7e
+        cc_mounts.handle(None, cc, self.mock_cloud, self.mock_log, [])
591b7e
+
591b7e
     def test_fstab_no_swap_device(self):
591b7e
         '''Ensure that cloud-init adds a discovered swap partition
591b7e
         to /etc/fstab.'''
591b7e
-- 
591b7e
1.8.3.1
591b7e