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