From 3277590399a8a71a320a6f681443580a82a8a3ff Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E7=8E=8B=E7=85=8E=E9=A5=BC?= <bin456789@gmail.com>
Date: Tue, 22 Aug 2023 04:17:05 +0800
Subject: [PATCH] cc_mounts: Use fallocate to create swapfile on btrfs (#4369)

Reference:https://github.com/canonical/cloud-init/commit/3277590399a8a71a320a6f681443580a82a8a3ff
Conflict:(1)format diff.
(2)change test_handler_mounts.py not test_cc_mounts.py.

Swapfile works fine with fallocate on btrfs.
Btrfs official document also use fallocate instead of dd.

See https://btrfs.readthedocs.io/en/latest/Swapfile.html
---
 cloudinit/config/cc_mounts.py                       | 2 +-
 tests/unittests/test_handler/test_handler_mounts.py | 4 +---
 2 files changed, 2 insertions(+), 4 deletions(-)

diff --git a/cloudinit/config/cc_mounts.py b/cloudinit/config/cc_mounts.py
index 54ca3f3..2d645b3 100644
--- a/cloudinit/config/cc_mounts.py
+++ b/cloudinit/config/cc_mounts.py
@@ -258,7 +258,7 @@ def create_swapfile(fname: str, size: str) -> None:
         subp.subp(["chattr", "+C", fname])
 
     if (fstype == "xfs" and
-            util.kernel_version() < (4, 18)) or fstype == "btrfs":
+            util.kernel_version() < (4, 18)):
         create_swap(fname, size, "dd")
     else:
         try:
diff --git a/tests/unittests/test_handler/test_handler_mounts.py b/tests/unittests/test_handler/test_handler_mounts.py
index 8a6f38c..6799c1e 100644
--- a/tests/unittests/test_handler/test_handler_mounts.py
+++ b/tests/unittests/test_handler/test_handler_mounts.py
@@ -232,9 +232,7 @@ class TestSwapFileCreation(test_helpers.FilesystemMockingTestCase):
         self.m_subp_subp.assert_has_calls([
             mock.call(["truncate", "-s", "0", self.swap_path]),
             mock.call(["chattr", "+C", self.swap_path]),
-            mock.call(['dd', 'if=/dev/zero',
-                       'of=' + self.swap_path,
-                       'bs=1M', 'count=0'], capture=True),
+            mock.call(["fallocate", "-l", "0M", self.swap_path], capture=True),
             mock.call(['mkswap', self.swap_path]),
             mock.call(['swapon', '-a'])])
 
-- 
2.33.0


