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