From 11a4fd1f80e32fd306e9fb8006321f303f7c91ba 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, 15 Aug 2023 05:08:35 +0800
Subject: [PATCH] cc_mounts: Fix swapfile not working on btrfs (#4319)

Reference:https://github.com/canonical/cloud-init/commit/11a4fd1f80e32fd306e9fb8006321f303f7c91ba
Conflict:(1)do not change tools/.github-cla-signers
(2)change test_handler_mounts.py not test_cc_mounts.py.
(3)format diff.

To make a swapfile work on btrfs, we need to create an empty file
and add the "no copy-on-write" attribute before making it a swapfile.

See https://btrfs.readthedocs.io/en/latest/Swapfile.html

Fixes GH-3713
LP: #1884127
---
 cloudinit/config/cc_mounts.py                       | 4 ++++
 tests/unittests/test_handler/test_handler_mounts.py | 2 ++
 2 files changed, 6 insertions(+)

diff --git a/cloudinit/config/cc_mounts.py b/cloudinit/config/cc_mounts.py
index 1c6b883..54ca3f3 100644
--- a/cloudinit/config/cc_mounts.py
+++ b/cloudinit/config/cc_mounts.py
@@ -253,6 +253,10 @@ def create_swapfile(fname: str, size: str) -> None:
 
     fstype = util.get_mount_info(swap_dir)[1]
 
+    if fstype == "btrfs":
+        subp.subp(["truncate", "-s", "0", fname])
+        subp.subp(["chattr", "+C", fname])
+
     if (fstype == "xfs" and
             util.kernel_version() < (4, 18)) or fstype == "btrfs":
         create_swap(fname, size, "dd")
diff --git a/tests/unittests/test_handler/test_handler_mounts.py b/tests/unittests/test_handler/test_handler_mounts.py
index 69e8b30..8a6f38c 100644
--- a/tests/unittests/test_handler/test_handler_mounts.py
+++ b/tests/unittests/test_handler/test_handler_mounts.py
@@ -230,6 +230,8 @@ class TestSwapFileCreation(test_helpers.FilesystemMockingTestCase):
 
         cc_mounts.handle(None, self.cc, self.mock_cloud, self.mock_log, [])
         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),
-- 
2.33.0


