Debian Codegraph @

tests/linux_kernel/helpers/test_swap.py

raw
1 # Copyright (c) Meta Platforms, Inc. and affiliates.
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3
4 import collections
5 import contextlib
6 import mmap
7 import os
8 from pathlib import Path
9 import re
10 import subprocess
11 import tempfile
12 from typing import NamedTuple
13
14 from drgn.helpers.linux.swap import (
15 for_each_swap_info,
16 swap_file_path,
17 swap_is_file,
18 swap_total_usage,
19 swap_usage_in_pages,
20 total_swapcache_pages,
21 )
22 from tests.linux_kernel import (
23 LinuxKernelTestCase,
24 MbrPartition,
25 MbrPartitionType,
26 fallocate,
27 meminfo_field_in_pages,
28 mkswap,
29 mount,
30 skip_unless_have_test_disk,
31 swapoff,
32 swapon,
33 umount,
34 write_mbr,
35 )
36
37
38 class SwapInfo(NamedTuple):
39 filename: str
40 type: str
41 size: int
42 used: int
43 priority: int
44
45
46 def iter_swaps():
47 with open("/proc/swaps", "rb") as f:
48 f.readline()
49 for line in f:
50 tokens = line.split()
51 yield SwapInfo(
52 filename=tokens[0].decode("unicode-escape"),
53 type=tokens[1].decode("ascii"),
54 size=int(tokens[2]) * 1024,
55 used=int(tokens[3]) * 1024,
56 priority=int(tokens[4]),
57 )
58
59
60 @contextlib.contextmanager
61 def tmp_swaps():
62 disk = os.environ["DRGN_TEST_DISK"]
63 swaps = []
64
65 with contextlib.ExitStack() as exit_stack:
66 write_mbr(
67 disk,
68 [
69 MbrPartition(
70 type=MbrPartitionType.LINUX_SWAP,
71 start=1024 * 1024,
72 size=8 * 1024 * 1024,
73 ),
74 MbrPartition(
75 type=MbrPartitionType.LINUX,
76 start=9 * 1024 * 1024,
77 size=8 * 1024 * 1024,
78 ),
79 ],
80 )
81
82 part_prefix = os.environ["DRGN_TEST_DISK"]
83 if part_prefix[:-1].isdigit():
84 part_prefix += "p"
85 part1 = part_prefix + "1"
86 part2 = part_prefix + "2"
87
88 mkswap(part1)
89 swapon(part1)
90 exit_stack.callback(swapoff, part1)
91 swaps.append((part1, False))
92
93 subprocess.check_call(["mke2fs", "-qF", part2])
94 tmp = Path(exit_stack.enter_context(tempfile.TemporaryDirectory()))
95 mount(part2, tmp, "ext2")
96 exit_stack.callback(umount, tmp)
97 swap_file = tmp / "swap_file"
98 fallocate(swap_file, 0, 1024 * 1024)
99 mkswap(swap_file)
100 swapon(swap_file)
101 exit_stack.callback(swapoff, swap_file)
102 swaps.append((swap_file, True))
103
104 yield swaps
105
106
107 @skip_unless_have_test_disk
108 class TestSwap(LinuxKernelTestCase):
109 @classmethod
110 def setUpClass(cls):
111 super().setUpClass()
112 cls.enterClassContext(tmp_swaps())
113
114 # There is no test_for_each_swap_info() because we test it implicitly in
115 # the other tests. These tests also handle duplicate swap filenames, which
116 # are unlikely but theoretically possible with namespace shenanigans.
117
118 def test_swap_file_path(self):
119 self.assertCountEqual(
120 [os.fsdecode(swap_file_path(si)) for si in for_each_swap_info(self.prog)],
121 [swap_info.filename for swap_info in iter_swaps()],
122 )
123
124 def test_swap_is_file(self):
125 self.assertCountEqual(
126 [
127 (os.fsdecode(swap_file_path(si)), swap_is_file(si))
128 for si in for_each_swap_info(self.prog)
129 ],
130 [
131 (swap_info.filename, swap_info.type == "file")
132 for swap_info in iter_swaps()
133 ],
134 )
135
136 def test_swap_usage_in_pages(self):
137 actual = collections.Counter()
138 for si in for_each_swap_info(self.prog):
139 actual[os.fsdecode(swap_file_path(si))] += (
140 swap_usage_in_pages(si) * mmap.PAGESIZE
141 )
142
143 expected = collections.Counter()
144 for swap_info in iter_swaps():
145 expected[swap_info.filename] += swap_info.used
146
147 for filename, used in expected.items():
148 # Generous delta to allow for stuff getting swapped in/out while
149 # the test is running.
150 self.assertAlmostEqual(used, actual[filename], delta=1024 * 1024 * 1024)
151
152 def test_swap_total_usage(self):
153 swap_usage = swap_total_usage(self.prog)
154
155 with open("/proc/meminfo", "r") as f:
156 for line in f:
157 if match := re.match(r"Swap(Total|Free):\s*([0-9]+)\s*kB", line):
158 value = int(match.group(2)) * 1024 // mmap.PAGESIZE
159 if match.group(1) == "Total":
160 pages = value
161 else:
162 free_pages = value
163
164 self.assertEqual(swap_usage.pages, pages)
165 # Generous delta to allow for stuff getting swapped in/out while the
166 # test is running.
167 self.assertAlmostEqual(
168 swap_usage.free_pages, free_pages, delta=1024 * 1024 * 1024
169 )
170
171 def test_total_swapcache_pages(self):
172 self.assertAlmostEqual(
173 total_swapcache_pages(self.prog),
174 meminfo_field_in_pages("SwapCached"),
175 delta=1024 * 1024 * 1024,
176 )