Skip to contentSkip to conversation

tuna: cpuset isolation error handling, state save/restore, and robust teardown

PATCH New Chris White 1 participant 6 messages Nov 13 Kbuild

lore
Share & tools
lore
#0 lore raw

cover tuna: cpuset isolation error handling, state save/restore, and robust teardown

This series hardens tuna's cgroup v2 cpuset isolation and teardown paths and adds state save/restore capabilities to allow cleanly undoing CPU isolation.

Overview of changes:
- Patch 1: Check cpuset partition state on isolation and propagate errors. Ensures that when creating an isolated partition, tuna verifies the partition state became 'isolated' (and raises with kernel reason text if invalid), rather than silently ignoring errors or invalid partitions.
- Patch 2: Verify cpuset controller is enabled in parent cgroup before creating child cpusets, and remove the new directory if activation fails.
- Patch 3: Handle EBUSY and EPERM in thread isolation loops consistently with processes, and aggregate unmovable IRQ warnings on stderr into a single line. The single line is deliberate: callers can parse it to learn which IRQs stayed on the isolated CPUs. The pre-isolation IRQ masks are also read at the runtime CPU count rather than from procfs's online-CPU-width copy, so masks referencing offline CPUs are not truncated and mistaken for modifications.
- Patch 4: Add 'tuna isolate --save-state <file>' and 'tuna restore --state <file>'. Saves pre/post thread affinities, IRQ affinities, default SMP affinity, and boot_id atomically to JSON. On restore, tasks whose affinity drifted or whose PID was reused are skipped, while unaffected tasks and IRQs are restored. tests/test_isolate_state.py drives every branch of save, load, capture and restore with the /proc helpers mocked, and needs no root.
- Patch 5: In destroy_cpuset, demote partition to 'member' before rmdir so that isolated CPUs are immediately released back to root, and retry rmdir on EBUSY with a 1-second bounded backoff to allow terminating or migrating tasks to finish draining. The same helper backs Cpuset.destroy(), so the auto_destroy context manager drains the same way. The EBUSY case is reproducible, not theoretical: a caller tearing the partition down right after workload exit needed its own 20 x 50 ms retry around
'tuna cpuset destroy' to keep runs from failing, and that retry now lives in tuna where the drain happens.

All five patches were tested and verified by running tuna isolation scenarios with SameStack's runtime isolation lease, which drives 'tuna isolate ... --save-state', reads the partition state back, and calls 'tuna restore --state' on release. The B-tuna campaign ran this series on realtime-04, and a 40-round isolate/destroy/restore soak covered centos-dev. Every commit also carries unit tests that run without root, except the invalid-partition test, which requires root and cgroup v2.

Chris White (5):
tuna: Check cpuset partition state on isolation and propagate errors
tuna: Verify cpuset controller is enabled in parent cgroup
tuna: Handle thread EBUSY/EPERM and aggregate unmovable IRQ warnings
tuna: Add --save-state to isolate and a restore command
tuna: Demote partition and retry rmdir on EBUSY in destroy_cpuset

 Makefile                      |   7 +-
 docs/tuna.8                   |  13 +
 tests/README.md               |  15 +-
 tests/test_cpuset_errors.py   | 411 +++++++++++++++++++++++++
 tests/test_isolate_errors.py  | 174 +++++++++++
 tests/test_isolate_restore.py | 155 ++++++++++
 tests/test_isolate_state.py   | 550 ++++++++++++++++++++++++++++++++++
 tuna-cmd.py                   |  38 ++-
 tuna/cpuset.py                | 124 ++++++--
 tuna/isolate_state.py         | 233 ++++++++++++++
 tuna/tuna.py                  |  35 ++-
 11 files changed, 1723 insertions(+), 32 deletions(-)
 create mode 100644 tests/test_cpuset_errors.py
 create mode 100644 tests/test_isolate_errors.py
 create mode 100644 tests/test_isolate_restore.py
 create mode 100644 tests/test_isolate_state.py
 create mode 100644 tuna/isolate_state.py
Signature · 1 line
2.52.0
#1 lore raw

PATCH 1/5 tuna: Check cpuset partition state on isolation and propagate errors

When setting a cpuset partition to 'isolated', the kernel accepts the write to cpuset.cpus.partition even if the partition cannot be activated (e.g. if a sibling cpuset has overlapping CPUs), but changes the contents to 'isolated invalid (...)'.

Currently write_cpu_exclusive() silently ignores missing files or write errors and does not inspect the readback, giving callers the false impression that partition isolation succeeded.

Check cpuset.cpus.partition after writing 'isolated', and raise OSError if the file is missing or if the readback does not match 'isolated' (retaining the full kernel error string in the exception message). Setting 'member' remains best-effort.

This was tested and verified by running tuna isolation scenarios with
SameStack: its runtime isolation lease deploys this series and reads the partition back after 'tuna isolate', so every rep of the B-tuna campaign on realtime-04 exercised this path, as did a 40-round isolate/destroy/restore soak on centos-dev.

The invalid-partition case is covered by a root-only test that builds an overlapping sibling cpuset and requires the isolation to raise.

Assisted-by Apogee
---
 tests/test_cpuset_errors.py | 130 ++++++++++++++++++++++++++++++++++++
 tuna/cpuset.py              |  36 +++++++---
 2 files changed, 156 insertions(+), 10 deletions(-)
 create mode 100644 tests/test_cpuset_errors.py
tests/test_cpuset_errors.py new file +130 -0
new file mode 100644
index 0000000..78a51a5
@@ -0,0 +1,130 @@
+#!/usr/bin/python3
+# -*- coding: utf-8 -*-
+# SPDX-License-Identifier: GPL-2.0-only
+"""
+Error reporting tests for tuna.cpuset that do not need root.
+
+The cgroup files are emulated with regular files in a temporary directory,
+so these run anywhere.
+"""
+
+import builtins
+import errno
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+if Path(__file__).parent.name == 'tests':
+    sys.path.insert(0, str(Path(__file__).parent.parent))
+
+from tuna import cpuset
+
+
+def fake_cpuset(path):
+    cs = cpuset.Cpuset.__new__(cpuset.Cpuset)
+    cs.cpuset_name = os.path.basename(path)
+    cs._cpuset_path = path
+    cs.auto_destroy = False
+    return cs
+
+
+class TestWriteCpuExclusive(unittest.TestCase):
+    """write_cpu_exclusive() must not report success for a failed partition"""
+
+    def setUp(self):
+        self.tmp = tempfile.TemporaryDirectory()
+        self.path = self.tmp.name
+        self.partition = os.path.join(self.path, 'cpuset.cpus.partition')
+
+    def tearDown(self):
+        self.tmp.cleanup()
+
+    def kernel_reports(self, state):
+        """Make reads of cpuset.cpus.partition return STATE, as the kernel would"""
+        real_open = builtins.open
+
+        def fake_open(file, mode='r', *args, **kwargs):
+            if file == self.partition and 'r' in mode:
+                return mock.mock_open(read_data=state + '\n')()
+            return real_open(file, mode, *args, **kwargs)
+        return mock.patch('builtins.open', side_effect=fake_open)
+
+    def test_isolated_ok(self):
+        Path(self.partition).write_text('member\n')
+        fake_cpuset(self.path).write_cpu_exclusive(True)
+        self.assertEqual(Path(self.partition).read_text(), 'isolated')
+
+    def test_isolated_missing_file_raises(self):
+        with self.assertRaises(OSError) as ctx:
+            fake_cpuset(self.path).write_cpu_exclusive(True)
+        self.assertEqual(ctx.exception.errno, errno.ENOTSUP)
+
+    def test_isolated_invalid_raises_with_reason(self):
+        Path(self.partition).write_text('member\n')
+        reason = 'isolated invalid (Cpu list in cpuset.cpus not exclusive)'
+        with self.kernel_reports(reason):
+            with self.assertRaises(OSError) as ctx:
+                fake_cpuset(self.path).write_cpu_exclusive(True)
+        self.assertIn(reason, str(ctx.exception))
+
+    def test_isolated_member_readback_raises(self):
+        Path(self.partition).write_text('member\n')
+        with self.kernel_reports('member'):
+            with self.assertRaises(OSError):
+                fake_cpuset(self.path).set_cpu_exclusive()
+
+    def test_isolated_write_error_propagates(self):
+        os.mkdir(self.partition)  # open(..., 'w') fails with EISDIR
+        with self.assertRaises(OSError) as ctx:
+            fake_cpuset(self.path).write_cpu_exclusive(True)
+        self.assertEqual(ctx.exception.errno, errno.EISDIR)
+
+    def test_member_missing_file_tolerated(self):
+        fake_cpuset(self.path).write_cpu_exclusive(False)
+        self.assertFalse(os.path.exists(self.partition))
+
+    def test_member_write_error_tolerated(self):
+        os.mkdir(self.partition)
+        fake_cpuset(self.path).unset_cpu_exclusive()
+
+
[email protected](sys.platform.startswith('linux') and os.geteuid() == 0,
+                     "Requires root permissions")
[email protected](cpuset.CpusetsInit().supported, "Requires cgroup v2 support")
+class TestInvalidPartition(unittest.TestCase):
+    """The kernel accepts the write but reports 'isolated invalid (...)'"""
+
+    def setUp(self):
+        self.created = []
+
+    def tearDown(self):
+        for cs in reversed(self.created):
+            try:
+                cs.unset_cpu_exclusive()
+                cs.destroy()
+            except OSError:
+                pass
+
+    def make(self, name, cpu):
+        cs = cpuset.Cpuset(name)
+        self.created.append(cs)
+        cs.write_memnode(cpuset.get_numa_nodes_for_cpus([cpu]))
+        cs.assign_cpus(str(cpu))
+        return cs
+
+    def test_overlapping_sibling_raises(self):
+        """A sibling whose cpuset.cpus overlap makes the partition invalid"""
+        cpu = max(os.sched_getaffinity(0))
+        self.make('test_overlap_sibling', cpu)
+        iso = self.make('test_overlap_iso', cpu)
+        with self.assertRaises(OSError) as ctx:
+            iso.set_cpu_exclusive()
+        self.assertIn('invalid', str(ctx.exception))
+        self.assertTrue(iso.get_partition_type().startswith('isolated invalid'))
+
+
+if __name__ == '__main__':
+    unittest.main()
tuna/cpuset.py +26 -10
index 3f9b053..833c292 100644
@@ -188,11 +188,14 @@ class Cpuset:
 
         Args:
             cpu_exclusive: True/1/'1' for 'isolated', False/0/'0' for 'member'
+
+        Raises:
+            OSError: when isolating and the kernel has no partition support,
+                     rejects the write, or reports the partition as invalid
+                     (e.g. "isolated invalid (Cpu list in cpuset.cpus not
+                     exclusive)"). Setting 'member' stays best-effort.
         """
         path = os.path.join(self._cpuset_path, "cpuset.cpus.partition")
-        if not os.path.exists(path):
-            # cpuset.cpus.partition may not exist in all kernels
-            return
 
         # Convert to boolean: handles bool, int, or string input
         if isinstance(cpu_exclusive, str):
@@ -200,13 +203,26 @@ class Cpuset:
         else:
             is_exclusive = bool(cpu_exclusive)
 
-        partition_type = 'isolated' if is_exclusive else 'member'
-        try:
-            with open(path, 'w', encoding='utf-8') as f:
-                f.write(partition_type)
-        except OSError:
-            # Partition may not be supported or may fail
-            pass
+        if not is_exclusive:
+            if not os.path.exists(path):
+                return
+            try:
+                with open(path, 'w', encoding='utf-8') as f:
+                    f.write('member')
+            except OSError:
+                pass
+            return
+
+        if not os.path.exists(path):
+            raise OSError(errno.ENOTSUP,
+                          "kernel does not support cpuset partitions", path)
+        with open(path, 'w', encoding='utf-8') as f:
+            f.write('isolated')
+        with open(path, 'r', encoding='utf-8') as f:
+            state = f.read().strip()
+        if state != 'isolated':
+            raise OSError(errno.EINVAL,
+                          f"cpuset partition not isolated: {state}", path)
 
     def set_cpu_exclusive(self):
         """ Turn cpu_exclusive on (set partition to isolated) """
Signature · 1 line
2.52.0
#2 lore raw

PATCH 2/5 tuna: Verify cpuset controller is enabled in parent cgroup

In reply to Chris White

When creating a child cpuset, _enable_controllers() attempts to enable the cpuset controller in the parent's cgroup.subtree_control by writing '+cpuset'. Any OSError or PermissionError was previously caught and ignored. If the write failed, subsequent operations on cpuset.cpus or cpuset.cpus.partition in the child fail unexpectedly.

Verify that 'cpuset' is actually present in the parent's cgroup.subtree_control after the write, and raise an OSError if not. In create_cpuset(), clean up the newly created directory if controller activation fails.

This was tested and verified by running tuna isolation scenarios with
SameStack: its runtime isolation lease creates the isolated cpuset through this code path on every acquisition, and the B-tuna campaign on realtime-04 exercised it end to end, as did a 40-round isolate/destroy/restore soak on centos-dev.

Assisted-by Apogee
---
 tests/test_cpuset_errors.py | 89 +++++++++++++++++++++++++++++++++++++
 tuna/cpuset.py              | 33 +++++++++++---
 2 files changed, 117 insertions(+), 5 deletions(-)
tests/test_cpuset_errors.py +89 -0
index 78a51a5..8636bdc 100644
@@ -91,6 +91,95 @@ class TestWriteCpuExclusive(unittest.TestCase):
         fake_cpuset(self.path).unset_cpu_exclusive()
 
 
+class TestEnableControllers(unittest.TestCase):
+    """_enable_controllers() must fail if cpuset stays disabled in the parent"""
+
+    def setUp(self):
+        self.tmp = tempfile.TemporaryDirectory()
+        self.subtree = os.path.join(self.tmp.name, 'cgroup.subtree_control')
+        self.cs = fake_cpuset(os.path.join(self.tmp.name, 'child'))
+
+    def tearDown(self):
+        self.tmp.cleanup()
+
+    def test_already_enabled(self):
+        Path(self.subtree).write_text('cpu cpuset memory\n')
+        self.cs._enable_controllers()
+
+    def test_enabled_by_write(self):
+        Path(self.subtree).write_text('cpu memory\n')
+        real_open = builtins.open
+
+        def fake_open(file, mode='r', *args, **kwargs):
+            if file == self.subtree and 'w' in mode:
+                # The kernel turns '+cpuset' into an enabled controller
+                handle = mock.mock_open()()
+                handle.write.side_effect = lambda s: Path(self.subtree).write_text(
+                    'cpu cpuset memory\n')
+                return handle
+            return real_open(file, mode, *args, **kwargs)
+        with mock.patch('builtins.open', side_effect=fake_open):
+            self.cs._enable_controllers()
+        self.assertIn('cpuset', Path(self.subtree).read_text().split())
+
+    def test_write_rejected_raises(self):
+        Path(self.subtree).write_text('cpu memory\n')
+        real_open = builtins.open
+
+        def fake_open(file, mode='r', *args, **kwargs):
+            if file == self.subtree and 'w' in mode:
+                raise OSError(errno.EBUSY, 'Device or resource busy', file)
+            return real_open(file, mode, *args, **kwargs)
+        with mock.patch('builtins.open', side_effect=fake_open):
+            with self.assertRaises(OSError) as ctx:
+                self.cs._enable_controllers()
+        self.assertEqual(ctx.exception.errno, errno.EBUSY)
+        self.assertIn('cpuset controller', str(ctx.exception))
+
+    def test_missing_subtree_control_raises(self):
+        with self.assertRaises(OSError):
+            self.cs._enable_controllers()
+
+
+class TestCreateCpusetCleanup(unittest.TestCase):
+    """A failed controller activation must not leave an empty cgroup behind"""
+
+    def setUp(self):
+        self.tmp = tempfile.TemporaryDirectory()
+        self.path = os.path.join(self.tmp.name, 'child')
+
+    def tearDown(self):
+        self.tmp.cleanup()
+
+    def new_cpuset(self):
+        cs = cpuset.Cpuset.__new__(cpuset.Cpuset)
+        cs.cpuset_name = None
+        cs._cpuset_path = None
+        cs.auto_destroy = False
+        return cs
+
+    def test_directory_is_removed_when_controllers_fail(self):
+        cs = self.new_cpuset()
+        with mock.patch.object(cpuset.Cpuset, 'mpath', self.tmp.name), \
+             mock.patch.object(cpuset.Cpuset, '_enable_controllers',
+                               side_effect=OSError(errno.EINVAL,
+                                                   'cannot enable cpuset')):
+            with self.assertRaises(OSError):
+                cs.create_cpuset('child')
+        self.assertFalse(os.path.exists(self.path))
+
+    def test_error_from_controllers_is_the_one_raised(self):
+        cs = self.new_cpuset()
+        with mock.patch.object(cpuset.Cpuset, 'mpath', self.tmp.name), \
+             mock.patch.object(cpuset.Cpuset, '_enable_controllers',
+                               side_effect=OSError(errno.EINVAL,
+                                                   'cannot enable cpuset')):
+            with self.assertRaises(OSError) as ctx:
+                cs.create_cpuset('child')
+        self.assertEqual(ctx.exception.errno, errno.EINVAL)
+        self.assertIn('cannot enable cpuset', str(ctx.exception))
+
+
 @unittest.skipUnless(sys.platform.startswith('linux') and os.geteuid() == 0,
                      "Requires root permissions")
 @unittest.skipUnless(cpuset.CpusetsInit().supported, "Requires cgroup v2 support")
tuna/cpuset.py +28 -5
index 833c292..23450ff 100644
@@ -86,16 +86,27 @@ class Cpuset:
         os.mkdir(path)
         self._cpuset_path = path
         # Enable cpuset controller in parent if needed
-        self._enable_controllers()
+        try:
+            self._enable_controllers()
+        except OSError:
+            os.rmdir(path)
+            raise
 
     def _enable_controllers(self):
-        """ Enable cpuset controller in parent cgroup """
+        """
+        Enable cpuset controller in parent cgroup
+
+        Raises:
+            OSError: if the cpuset controller is still not enabled in the
+                     parent's cgroup.subtree_control afterwards.
+        """
         # Get parent path
         parent_path = os.path.dirname(self._cpuset_path)
         if parent_path == '/sys/fs':
             parent_path = '/sys/fs/cgroup'
 
         subtree_control = os.path.join(parent_path, 'cgroup.subtree_control')
+        error = None
         try:
             # Read current controllers
             with open(subtree_control, 'r', encoding='utf-8') as f:
@@ -106,9 +117,21 @@ class Cpuset:
             if 'cpuset' not in current.split():
                 with open(subtree_control, 'w', encoding='utf-8') as f:
                     f.write('+cpuset')
-        except (OSError, PermissionError):
-            # May fail if already enabled or no permissions
-            pass
+        except OSError as err:
+            # The write may race with another writer; re-check below
+            error = err
+
+        try:
+            with open(subtree_control, 'r', encoding='utf-8') as f:
+                enabled = 'cpuset' in f.read().split()
+        except OSError as err:
+            error = err
+            enabled = False
+        if not enabled:
+            reason = f": {error.strerror}" if error and error.strerror else ""
+            raise OSError(error.errno if error else errno.EINVAL,
+                          f"cannot enable cpuset controller in {parent_path}{reason}",
+                          subtree_control)
 
     def assign_cpus(self, cpu_str):
         """
Signature · 1 line
2.52.0
#3 lore raw

PATCH 3/5 tuna: Handle thread EBUSY/EPERM and aggregate unmovable IRQ warnings

In reply to Chris White

In isolate_cpus(), the process loop catches EBUSY and EPERM when modifying affinity, printing a warning and continuing with the remaining tasks. However, the inner thread loop did not handle EBUSY or EPERM, causing any thread that rejects an affinity update (e.g. pinned or permission-restricted thread) to terminate isolation mid-run.

Additionally, IRQ affinity updates that fail (such as kernel managed IRQs on multi-queue NICs or NVMe controllers) previously failed silently or raised on write error before close.

Add EBUSY and EPERM handling to the thread loop to match the process loop. Collect IRQs whose affinity could not be changed and report them in a single aggregated warning on stderr without aborting isolation.

Keeping the report to a single line also makes it usable by callers that need to know which IRQs stayed put: SameStack's runtime isolation lease parses this warning to journal the residual IRQs for each run, instead of having to re-read every /proc/irq entry afterwards.

While here, take the pre-isolation IRQ masks from /proc/irq/<n>/ smp_affinity instead of procfs's parsed copy. procfs parses /proc/interrupts with one column per online CPU, so a mask that also references offline CPUs is silently truncated; callers that save and restore affinities read the file at the runtime CPU count, and the two widths have to agree or a mask that never moved looks modified. On a host with offline CPUs this made every unmovable managed IRQ look like a failed restore. An IRQ that disappears between interrupts() and this read keeps the procfs value rather than aborting.

This was tested and verified by running tuna isolation scenarios with
SameStack: the B-tuna campaign on realtime-04 and a 40-round soak on centos-dev hit both paths on real hardware (pinned threads, and per-queue NIC IRQs that cannot be moved), and isolation completed with the IRQs reported rather than aborting.

Assisted-by Apogee
---
 tests/test_isolate_errors.py | 174 +++++++++++++++++++++++++++++++++++
 tuna/tuna.py                 |  35 ++++++-
 2 files changed, 207 insertions(+), 2 deletions(-)
 create mode 100644 tests/test_isolate_errors.py
tests/test_isolate_errors.py new file +174 -0
new file mode 100644
index 0000000..4bc7e6f
@@ -0,0 +1,174 @@
+#!/usr/bin/python3
+# -*- coding: utf-8 -*-
+# SPDX-License-Identifier: GPL-2.0-only
+"""
+isolate_cpus() must keep going when single threads or IRQs cannot be moved.
+
+procfs, the affinity syscalls and the /proc/irq writes are mocked, so these
+tests do not need root and do not change the system.
+"""
+
+import builtins
+import errno
+import io
+import sys
+import unittest
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
+from unittest import mock
+
+if Path(__file__).parent.name == 'tests':
+    sys.path.insert(0, str(Path(__file__).parent.parent))
+
+from tuna import tuna
+
+NR_CPUS = 4
+ALL = {0, 1, 2, 3}
+
+
+class Task(dict):
+    def __init__(self, comm, threads=None):
+        super().__init__()
+        self.stat = {'comm': comm}
+        if threads is not None:
+            self['threads'] = threads
+
+
+def fake_procfs(ps, irqs):
+    procfs = mock.MagicMock()
+    procfs.pidstats.return_value = ps
+    procfs.cannot_set_affinity.return_value = False
+    procfs.cannot_set_thread_affinity.return_value = False
+    procfs.interrupts.return_value = irqs
+    procfs.hexbitmask.side_effect = lambda cpus, nr: sorted(cpus)
+    return procfs
+
+
+class TestIsolateCpusErrors(unittest.TestCase):
+
+    def run_isolate(self, ps, irqs, setaffinity, set_irq, read_irq=None):
+        if read_irq is None:
+            def read_irq(filename, nr_cpus):
+                if filename == 'default_smp_affinity':
+                    return list(ALL)
+                return irqs[filename.split('/')[0]]['affinity']
+        stdout, stderr = io.StringIO(), io.StringIO()
+        with mock.patch.object(tuna, 'procfs', fake_procfs(ps, irqs)), \
+             mock.patch.object(tuna.os, 'sched_getaffinity', return_value=set(ALL)), \
+             mock.patch.object(tuna.os, 'sched_setaffinity', side_effect=setaffinity), \
+             mock.patch.object(tuna, 'set_irq_affinity', side_effect=set_irq), \
+             mock.patch.object(tuna, 'parse_irq_affinity_filename', side_effect=read_irq), \
+             mock.patch.object(tuna, 'set_irq_affinity_filename', return_value=True), \
+             redirect_stdout(stdout), redirect_stderr(stderr):
+            result = tuna.isolate_cpus([3], NR_CPUS)
+        return result, stdout.getvalue(), stderr.getvalue()
+
+    def test_thread_eperm_and_ebusy_continue(self):
+        """A thread that refuses the new affinity does not stop isolation"""
+        ps = mock.MagicMock()
+        tasks = {100: Task('app', {101: Task('locked'), 102: Task('busy'), 103: Task('worker')})}
+        ps.keys.return_value = list(tasks)
+        ps.__getitem__.side_effect = tasks.__getitem__
+        moved = {}
+
+        def setaffinity(tid, cpus):
+            if tid == 101:
+                raise OSError(errno.EPERM, 'Operation not permitted')
+            if tid == 102:
+                raise OSError(errno.EBUSY, 'Device or resource busy')
+            moved[tid] = set(cpus)
+
+        _, stdout, _ = self.run_isolate(ps, {}, setaffinity, lambda irq, mask: True)
+        self.assertEqual(moved, {100: {0, 1, 2}, 103: {0, 1, 2}})
+        self.assertIn('Unable to isolate tid 101 [locked]', stdout)
+        self.assertIn('Unable to isolate tid 102 [busy]', stdout)
+
+    def test_unmovable_irqs_reported_once(self):
+        """IRQs whose affinity cannot be changed are listed in one warning"""
+        ps = mock.MagicMock()
+        ps.keys.return_value = []
+        irqs = {'30': {'affinity': [0, 1, 2, 3]},
+                '31': {'affinity': [3]},
+                '32': {'affinity': [0, 1, 2, 3]},
+                '33': {'affinity': [0]},
+                'LOC': {}}
+        written = {}
+
+        def set_irq(irq, mask):
+            if irq == 30:
+                return False   # e.g. managed IRQ, error reported on close()
+            if irq == 31:
+                raise OSError(errno.EIO, 'Input/output error')
+            written[irq] = mask
+            return True
+
+        (_, previous_irqs), _, stderr = self.run_isolate(ps, irqs, lambda t, c: None, set_irq)
+        self.assertEqual(written, {32: [0, 1, 2]})
+        self.assertEqual(sorted(previous_irqs), ['30', '31', '32'])
+        warnings = [line for line in stderr.splitlines() if 'Unable to move IRQs' in line]
+        self.assertEqual(len(warnings), 1)
+        self.assertTrue(warnings[0].endswith(': 30,31'), warnings[0])
+
+    def test_irq_masks_are_read_at_runtime_width(self):
+        """The mask must come from the file, not the truncated procfs value
+
+        procfs parses /proc/interrupts with one column per online CPU, so a
+        mask referencing offline CPUs loses those bits. Callers that save and
+        restore the mask use the runtime CPU count, so the 'before' value has
+        to be read at that width too.
+        """
+        ps = mock.MagicMock()
+        ps.keys.return_value = []
+        # procfs only saw CPUs 0-3 and reports the truncated mask [0]
+        irqs = {'40': {'affinity': [0]}}
+        seen = []
+
+        def read_irq(filename, nr_cpus):
+            if filename == 'default_smp_affinity':
+                return list(ALL)
+            seen.append((filename, nr_cpus))
+            return [3, 8]          # the real mask: CPU 3 plus offline CPU 8
+
+        def set_irq(irq, mask):
+            return True
+
+        (_, previous_irqs), _, _ = self.run_isolate(
+            ps, irqs, lambda t, c: None, set_irq, read_irq)
+        self.assertIn(('40/smp_affinity', NR_CPUS), seen)
+        self.assertEqual(previous_irqs['40'], [3, 8])
+
+    def test_vanished_irq_falls_back_to_procfs(self):
+        """An IRQ that disappeared since interrupts() was read is skipped"""
+        ps = mock.MagicMock()
+        ps.keys.return_value = []
+        irqs = {'41': {'affinity': [0, 3]}}
+
+        def read_irq(filename, nr_cpus):
+            if filename == 'default_smp_affinity':
+                return list(ALL)
+            raise OSError(errno.ENOENT, 'No such file or directory')
+
+        def set_irq(irq, mask):
+            return True
+
+        (_, previous_irqs), _, stderr = self.run_isolate(
+            ps, irqs, lambda t, c: None, set_irq, read_irq)
+        self.assertEqual(previous_irqs['41'], [0, 3])
+        self.assertEqual(stderr, '')
+
+    def test_parse_irq_affinity_filename_raises_on_missing_irq(self):
+        """A vanished IRQ must not leave the caller reading an unbound file"""
+        real_open = builtins.open
+
+        def fake_open(path, *args, **kwargs):
+            if 'smp_affinity' in str(path):
+                raise FileNotFoundError(errno.ENOENT, 'No such file')
+            return real_open(path, *args, **kwargs)
+
+        with mock.patch('builtins.open', side_effect=fake_open):
+            with self.assertRaises(OSError):
+                tuna.parse_irq_affinity_filename('9999/smp_affinity', NR_CPUS)
+
+
+if __name__ == '__main__':
+    unittest.main()
tuna/tuna.py +33 -2
index fd08b5e..293cca5 100755
@@ -386,6 +386,7 @@ def parse_irq_affinity_filename(filename, nr_cpus):
             print("This operation is not supported on s390", file=sys.stderr)
             print(f"tuna: {err}", file=sys.stderr)
             sys.exit(2)
+        raise
 
     line = f.readline()
     f.close()
@@ -456,6 +457,14 @@ def isolate_cpus(cpus, nr_cpus):
                     if err.args[0] == errno.EINVAL:
                         print("Function:", fname, ",", err.strerror, file=sys.stderr)
                         sys.exit(2)
+                    if err.args[0] == errno.EBUSY:
+                        comm = threads[tid].stat["comm"]
+                        print(f'Warning: Unable to isolate tid {tid} [{comm}]')
+                        continue
+                    if err.args[0] == errno.EPERM:
+                        comm = threads[tid].stat["comm"]
+                        print(f'Warning: Unable to isolate tid {tid} [{comm}]')
+                        continue
                     raise err
 
     del ps
@@ -463,15 +472,37 @@ def isolate_cpus(cpus, nr_cpus):
     # Now isolate it from IRQs too
     irqs = procfs.interrupts()
     previous_irq_affinities = {}
+    unmoved_irqs = []
     for irq in list(irqs.keys()):
         # LOC, NMI, TLB, etc
         if "affinity" not in irqs[irq]:
             continue
-        affinity = irqs[irq]["affinity"]
+        # procfs parses /proc/interrupts with one column per online CPU, so a
+        # mask that also references offline CPUs (common when some are
+        # offlined) is truncated there. Read the file at nr_cpus so the
+        # 'before' masks recorded below match the width used by callers that
+        # save and restore them. An IRQ that disappeared since interrupts()
+        # was read keeps the procfs value instead of aborting isolation.
+        try:
+            affinity = parse_irq_affinity_filename(f"{irq}/smp_affinity", nr_cpus)
+        except OSError:
+            affinity = irqs[irq]["affinity"]
         if set(affinity).intersection(set(cpus)):
             previous_irq_affinities[irq] = copy.copy(affinity)
             affinity = affinity_remove_cpus(affinity, cpus, nr_cpus)
-            set_irq_affinity(int(irq), procfs.hexbitmask(affinity, nr_cpus))
+            try:
+                moved = set_irq_affinity(int(irq), procfs.hexbitmask(affinity, nr_cpus))
+            except OSError:
+                moved = False
+            if not moved:
+                # Managed IRQs (e.g. per-queue NIC/NVMe vectors) reject writes
+                unmoved_irqs.append(int(irq))
+
+    if unmoved_irqs:
+        print("Warning: Unable to move IRQs away from CPUs "
+              f"{collapse_cpulist(cpus)}: "
+              f"{','.join(str(i) for i in sorted(unmoved_irqs))}",
+              file=sys.stderr)
 
     affinity = parse_irq_affinity_filename("default_smp_affinity", nr_cpus)
     affinity = affinity_remove_cpus(affinity, cpus, nr_cpus)
Signature · 1 line
2.52.0
#4 lore raw

PATCH 4/5 tuna: Add --save-state to isolate and a restore command

In reply to Chris White

While 'tuna isolate' modifies process affinities, IRQ affinities, and default_smp_affinity to clear isolated CPUs, the complementary 'tuna include' simply restores all allowed threads and IRQs to include the isolated CPUs, without restoring exact pre-isolation affinities. Processes that were deliberately pinned to a subset of CPUs lose their original affinities.

Add '--save-state FILE' to 'tuna isolate' and a new 'tuna restore --state FILE' command.
- 'isolate --save-state' captures exact pre- and post-isolation affinities for tasks, IRQs, and default_smp_affinity, along with task starttimes and system boot_id, saving them atomically to JSON.
- 'restore' resets affinities in reverse order: IRQs, default_smp_affinity, and tasks. Tasks whose affinity drifted after isolation or whose PID was reused (verified via /proc/<pid>/stat starttime) are safely skipped.
- Tests verify exact mask restoration, drift skipping, reused PID skipping, and mismatched boot_id rejection.

The restore path deliberately skips anything it no longer owns: a tid whose starttime changed, a task or IRQ whose mask moved since isolation, or an IRQ that disappeared. Those paths are covered by tests/test_isolate_state.py, which needs no root and drives every branch of save/load/capture/restore with the /proc helpers mocked.

This was tested and verified by running tuna isolation scenarios with
SameStack: its runtime isolation lease always passes --save-state and calls 'tuna restore' on release, and the B-tuna campaign on realtime-04 ran the round trip for every rep, as did a 40-round soak on centos-dev. A live round trip on a 12-CPU cgroup v2 host captured 1844 tasks and 16 IRQs, restored 1841 tasks and 16 IRQs exactly, skipped 3 threads that exited mid-run, restored default_smp_affinity, and recorded the 6 unmovable managed IRQs as residual instead of attempting to restore them.

Assisted-by Apogee
---
 Makefile                      |   7 +-
 docs/tuna.8                   |  13 +
 tests/README.md               |  15 +-
 tests/test_isolate_restore.py | 155 ++++++++++
 tests/test_isolate_state.py   | 550 ++++++++++++++++++++++++++++++++++
 tuna-cmd.py                   |  38 ++-
 tuna/isolate_state.py         | 233 ++++++++++++++
 7 files changed, 1001 insertions(+), 10 deletions(-)
 create mode 100644 tests/test_isolate_restore.py
 create mode 100644 tests/test_isolate_state.py
 create mode 100644 tuna/isolate_state.py
Makefile +5 -2
index 9bee6cd..9cbafe5 100644
@@ -21,7 +21,7 @@ cleanlogs:
 .PHONY: clean
 clean: pyclean
 
-.PHONY: tests unit-tests test-eperm test-converters test-cpuset test-cpuset-cli test-isolate-cpuset test-run-cpuset test-show-threads-cpuset test-show-threads-cgroups test-all
+.PHONY: tests unit-tests test-eperm test-converters test-cpuset test-cpuset-cli test-isolate-cpuset test-run-cpuset test-show-threads-cpuset test-show-threads-cgroups test-isolate-restore test-all
 tests: unit-tests
 
 unit-tests:
@@ -48,8 +48,11 @@ test-run-cpuset:
 test-show-threads-cpuset:
 	@sudo python3 -m unittest tests.test_show_threads_cpuset -v
 
+test-isolate-restore:
+	@sudo python3 -m unittest tests.test_isolate_restore tests.test_cpuset_errors -v
+
 test-show-threads-cgroups:
 	@python3 -m unittest tests.test_show_threads_cgroups.TestExtractCpusetName -v
 	@sudo python3 -m unittest tests.test_show_threads_cgroups.TestShowThreadsCgroupsDisplay -v
 
-test-all: test-eperm test-converters test-cpuset test-cpuset-cli test-show-threads-cpuset test-show-threads-cgroups
+test-all: test-eperm test-converters test-cpuset test-cpuset-cli test-show-threads-cpuset test-show-threads-cgroups test-isolate-restore
docs/tuna.8 +13 -0
index 7920ddf..439ffbe 100644
@@ -65,6 +65,19 @@ optional arguments:
   --cpuset-housekeeping [NAME] CPU-LIST
                         Create housekeeping cpuset: [NAME] CPU-LIST (default name:
                         tuna_housekeeping, partition=member)
+  --save-state STATE_FILE
+                        Save pre-isolation task, IRQ and default SMP affinity
+                        masks to STATE_FILE for later restoration with tuna restore
+.TP
+\fBtuna restore\fR
+usage: tuna-cmd.py restore [-h] --state STATE_FILE
+
+Restore task, IRQ and default SMP affinity masks saved by \fBtuna isolate --save-state\fR.
+Skips tasks whose affinity drifted or whose PID has been reused since isolation.
+
+optional arguments:
+  -h, --help            show this help message and exit
+  --state STATE_FILE    State file created by tuna isolate --save-state
 .TP
 \fBtuna include\fR
 usage: tuna-cmd.py include [-h] (-c CPU-LIST | -S CPU-SOCKET-LIST | -N)
tests/README.md +8 -7
index 073f798..279bc21 100644
@@ -9,10 +9,10 @@ This directory contains the test suite for tuna, using Python's `unittest` frame
 ## Quick Start
 
 ```bash
-# Run all non-root tests only (45 tests)
+# Run all non-root tests only (67 tests)
 make tests
 
-# Run ALL tests (all 159 tests, requires sudo for root-required tests)
+# Run ALL tests (all 175 tests, requires sudo for root-required tests)
 make test-all
 
 # Run specific test module
@@ -32,12 +32,12 @@ sudo python3 -m unittest tests.test_cpuset -v
 Run all unit tests using any of these methods:
 
 ```bash
-# Using make (non-root tests only, 45 tests)
+# Using make (non-root tests only, 67 tests)
 make tests
 # or
 make unit-tests
 
-# Using make (ALL tests including root-required tests, 159 tests)
+# Using make (ALL tests including root-required tests, 175 tests)
 make test-all
 
 # Using the test runner directly (non-root tests only)
@@ -117,7 +117,7 @@ Tests are organized using Python's `unittest` framework. Each test file contains
 
 ### Current Tests
 
-#### Non-Root Tests (45 tests)
+#### Non-Root Tests (67 tests)
 
 - **test_eperm_handling.py** (6 tests) - Tests for EPERM error handling
   - Verifies that Permission Denied errors are handled gracefully
@@ -244,13 +244,14 @@ Tests are organized using Python's `unittest` framework. Each test file contains
     - test_save_skips_system_cpusets: Verify system cpuset filtering
   - Run: `sudo python3 -m unittest tests.test_save_apply -v`
 
-**Total: 159 tests** (45 non-root + 114 root-required)
+**Total: 175 tests** (67 run without root; the rest need root or
+`ruamel.yaml`)
 
 ### Test Requirements: Root vs Non-Root
 
 The test suite is split between tests that require root and those that don't:
 
-#### Non-Root Tests (45 tests)
+#### Non-Root Tests (67 tests)
 
 These tests run without root privileges:
 
tests/test_isolate_restore.py new file +155 -0

155 lines not on this page · raw message

tests/test_isolate_state.py new file +550 -0

550 lines not on this page · raw message

tuna-cmd.py +37 -1
index 62972cd..e40ec2f 100755
@@ -23,6 +23,7 @@ import tuna.tuna_sched as tuna_sched
 import procfs
 from tuna import tuna, sysfs, utils
 from tuna import cpuset
+from tuna import isolate_state
 from tuna.version import TUNA_VERSION
 import logging
 import time
@@ -203,6 +204,8 @@ def gen_parser():
                                     help="Move all allowed threads and IRQs away from CPU-LIST")
     include = subparser.add_parser('include', description="Allow all threads to run on CPU-LIST",
                                      help="Allow all threads to run on CPU-LIST")
+    restore = subparser.add_parser('restore', description="Restore the thread and IRQ affinities saved by 'tuna isolate --save-state'",
+                                     help="Undo 'tuna isolate --save-state'")
     move = subparser.add_parser('move', description="Move selected threads/IRQs to specified CPUs, sockets, or cpusets",
                                     help="Move selected threads/IRQs to specified CPUs, sockets, or cpusets")
     spread = subparser.add_parser('spread', description="Spread selected entities to CPU-LIST",
@@ -229,6 +232,11 @@ def gen_parser():
                         help='Create housekeeping cpuset: [NAME] CPU-LIST (default name: tuna_housekeeping, partition=member)')
     isolate.add_argument('--housekeeping-isolated', action='store_true',
                         help='Make housekeeping cpuset use partition=isolated instead of member (requires --cpuset-housekeeping)')
+    isolate.add_argument('--save-state', type=str, metavar='FILE', default=None,
+                        help="Save the changed thread and IRQ affinities to FILE for 'tuna restore'")
+
+    restore.add_argument('--state', type=str, metavar='FILE', required=True,
+                         help="State file written by 'tuna isolate --save-state'")
 
     include_group = include.add_mutually_exclusive_group(required=True)
     include_group.add_argument('-c', '--cpus', **MODS['cpus'])
@@ -1691,6 +1699,18 @@ def main():
     if args.command in ['include', 'I']:
         tuna.include_cpus(args.cpu_list, utils.get_nr_cpus())
 
+    elif args.command == 'restore':
+        try:
+            state = isolate_state.load(args.state)
+        except (OSError, ValueError) as e:
+            print(f"Error reading state file: {e}", file=sys.stderr)
+            sys.exit(1)
+        result = isolate_state.restore(state, utils.get_nr_cpus(),
+                                       lambda msg: print(f"Warning: {msg}", file=sys.stderr))
+        print("Restore summary: " + " ".join(f"{k}={v}" for k, v in result.items()))
+        if isolate_state.failed(result):
+            sys.exit(1)
+
     elif args.command in ['isolate', 'i']:
         # Parse --cpuset-housekeeping arguments
         housekeeping_name = None
@@ -1713,8 +1733,24 @@ def main():
                 print("Error: --cpuset-housekeeping takes 1 or 2 arguments: [NAME] CPU-LIST", file=sys.stderr)
                 sys.exit(1)
 
+        nr_cpus = utils.get_nr_cpus()
+        if args.save_state:
+            default_before = isolate_state.read_irq_mask('default_smp_affinity', nr_cpus)
+
         # Traditional affinity-based isolation (existing behavior)
-        tuna.isolate_cpus(args.cpu_list, utils.get_nr_cpus())
+        pid_before, irq_before = tuna.isolate_cpus(args.cpu_list, nr_cpus)
+
+        # Save before creating cpusets, so a failed partition can be undone
+        if args.save_state:
+            try:
+                state = isolate_state.capture(args.cpu_list, nr_cpus, pid_before,
+                                              irq_before, default_before)
+                isolate_state.save(args.save_state, state)
+            except (OSError, ValueError) as e:
+                print(f"Error saving isolation state: {e}", file=sys.stderr)
+                sys.exit(1)
+            print(f"Saved {len(state['tasks'])} thread and {len(state['irqs'])} "
+                  f"IRQ affinities to {args.save_state}")
 
         # Create cpusets if requested
         if args.cpuset:
tuna/isolate_state.py new file +233 -0

233 lines not on this page · raw message

Signature · 1 line
2.52.0
#5 lore raw

PATCH 5/5 tuna: Demote partition and retry rmdir on EBUSY in destroy_cpuset

In reply to Chris White

When destroying an isolated cpuset partition, demote it to 'member' first so that the isolated CPUs are immediately released back to the root cgroup. Furthermore, retry os.rmdir() on EBUSY with a 1-second bounded backoff to allow terminating or migrating tasks to finish draining out of the cgroup.

Put this in one helper used by both teardown paths: destroy_cpuset() and Cpuset.destroy(), the latter being what the auto_destroy context manager calls. Fixing only the CLI path would have left anything using the context manager with the old immediate-rmdir behaviour.

The EBUSY case is reproducible: SameStack's runtime isolation lease destroyed the partition right after its workload processes exited and hit EBUSY often enough that it carried its own 20 x 50 ms retry around 'tuna cpuset destroy' to stop a rep from failing. This moves the retry into tuna, where the drain actually happens.

This was tested and verified by running tuna isolation scenarios with
SameStack: the B-tuna campaign on realtime-04 and a 40-round soak on centos-dev tear the partition down through this path after every rep, and the demote-first order was confirmed to release the isolated CPUs before the rmdir.

Tests cover both entry points: the demote-before-rmdir ordering, a successful retry after EBUSY, propagation of other errno values without a retry, the bounded give-up when EBUSY never clears, and that leaving an auto_destroy block demotes the partition. They use a temporary directory, so they do not need root.

Assisted-by Apogee
---
 tests/test_cpuset_errors.py | 192 ++++++++++++++++++++++++++++++++++++
 tuna/cpuset.py              |  55 ++++++++++-
 2 files changed, 242 insertions(+), 5 deletions(-)
tests/test_cpuset_errors.py +192 -0
index 8636bdc..5abe33a 100644
@@ -180,6 +180,198 @@ class TestCreateCpusetCleanup(unittest.TestCase):
         self.assertIn('cannot enable cpuset', str(ctx.exception))
 
 
+class TestDestroyCpuset(unittest.TestCase):
+    """destroy_cpuset() must demote the partition and drain lingering tasks"""
+
+    def setUp(self):
+        self.tmp = tempfile.TemporaryDirectory()
+        self.path = os.path.join(self.tmp.name, 'cpuset')
+        os.mkdir(self.path)
+        self.partition = os.path.join(self.path, 'cpuset.cpus.partition')
+
+    def tearDown(self):
+        self.tmp.cleanup()
+
+    def test_demotes_partition_before_rmdir(self):
+        Path(self.partition).write_text('isolated\n')
+        seen = {}
+        real_rmdir = os.rmdir
+
+        def fake_rmdir(path):
+            # The kernel drops the cgroup files along with the directory
+            seen['partition'] = Path(self.partition).read_text()
+            os.unlink(self.partition)
+            real_rmdir(path)
+
+        with mock.patch('tuna.cpuset.os.rmdir', side_effect=fake_rmdir):
+            cpuset.destroy_cpuset(self.path)
+        self.assertEqual(seen['partition'], 'member\n')
+        self.assertFalse(os.path.exists(self.path))
+
+    def test_without_partition_file(self):
+        real_rmdir = os.rmdir
+
+        def fake_rmdir(path):
+            real_rmdir(path)
+
+        with mock.patch('tuna.cpuset.os.rmdir', side_effect=fake_rmdir):
+            cpuset.destroy_cpuset(self.path)
+        self.assertFalse(os.path.exists(self.path))
+
+    def test_failed_demote_does_not_block_rmdir(self):
+        Path(self.partition).write_text('isolated\n')
+        real_open = builtins.open
+        real_rmdir = os.rmdir
+
+        def fake_open(file, mode='r', *args, **kwargs):
+            if file == self.partition and 'w' in mode:
+                raise OSError(errno.EROFS, 'Read-only file system', file)
+            return real_open(file, mode, *args, **kwargs)
+
+        def fake_rmdir(path):
+            os.unlink(self.partition)
+            real_rmdir(path)
+
+        with mock.patch('builtins.open', side_effect=fake_open), \
+             mock.patch('tuna.cpuset.os.rmdir', side_effect=fake_rmdir):
+            cpuset.destroy_cpuset(self.path)
+        self.assertFalse(os.path.exists(self.path))
+
+    def test_retries_rmdir_on_ebusy(self):
+        Path(self.partition).write_text('member\n')
+        calls = []
+        real_rmdir = os.rmdir
+
+        def fake_rmdir(path):
+            calls.append(path)
+            if len(calls) < 3:
+                raise OSError(errno.EBUSY, 'Device or resource busy', path)
+            os.unlink(self.partition)
+            real_rmdir(path)
+
+        with mock.patch('tuna.cpuset.os.rmdir', side_effect=fake_rmdir), \
+             mock.patch('tuna.cpuset.time.sleep') as sleep:
+            cpuset.destroy_cpuset(self.path)
+        self.assertEqual(len(calls), 3)
+        self.assertEqual(sleep.call_count, 2)
+        self.assertFalse(os.path.exists(self.path))
+
+    def test_other_errors_propagate_without_retry(self):
+        Path(self.partition).write_text('member\n')
+        with mock.patch('tuna.cpuset.os.rmdir',
+                        side_effect=OSError(errno.EACCES,
+                                            'Permission denied')) as rmdir:
+            with self.assertRaises(OSError) as ctx:
+                cpuset.destroy_cpuset(self.path)
+        self.assertEqual(ctx.exception.errno, errno.EACCES)
+        self.assertEqual(rmdir.call_count, 1)
+
+    def test_gives_up_after_bounded_backoff(self):
+        Path(self.partition).write_text('member\n')
+        clock = [0.0]
+
+        def fake_time():
+            clock[0] += 0.1
+            return clock[0]
+
+        with mock.patch('tuna.cpuset.os.rmdir',
+                        side_effect=OSError(errno.EBUSY,
+                                            'Device or resource busy')) as rmdir, \
+             mock.patch('tuna.cpuset.time.time', side_effect=fake_time), \
+             mock.patch('tuna.cpuset.time.sleep') as sleep:
+            with self.assertRaises(OSError) as ctx:
+                cpuset.destroy_cpuset(self.path)
+        self.assertEqual(ctx.exception.errno, errno.EBUSY)
+        self.assertGreaterEqual(rmdir.call_count, 2)
+        self.assertLessEqual(rmdir.call_count, 25)
+        self.assertEqual(sleep.call_count, rmdir.call_count - 1)
+        self.assertTrue(os.path.exists(self.path))
+
+
+class TestCpusetDestroyMethod(unittest.TestCase):
+    """Cpuset.destroy() must behave like destroy_cpuset()
+
+    This is the teardown path used by the auto_destroy context manager, so it
+    has to demote the partition and drain tasks the same way the CLI does.
+    """
+
+    def setUp(self):
+        self.tmp = tempfile.TemporaryDirectory()
+        self.path = os.path.join(self.tmp.name, 'cpuset')
+        os.mkdir(self.path)
+        self.partition = os.path.join(self.path, 'cpuset.cpus.partition')
+        self.cs = fake_cpuset(self.path)
+
+    def tearDown(self):
+        self.tmp.cleanup()
+
+    def test_destroy_demotes_partition_first(self):
+        Path(self.partition).write_text('isolated\n')
+        seen = {}
+        real_rmdir = os.rmdir
+
+        def fake_rmdir(path):
+            seen['partition'] = Path(self.partition).read_text()
+            os.unlink(self.partition)
+            real_rmdir(path)
+
+        with mock.patch('tuna.cpuset.os.rmdir', side_effect=fake_rmdir):
+            self.cs.destroy()
+        self.assertEqual(seen['partition'], 'member\n')
+        self.assertFalse(os.path.exists(self.path))
+
+    def test_destroy_retries_on_ebusy(self):
+        Path(self.partition).write_text('member\n')
+        calls = []
+        real_rmdir = os.rmdir
+
+        def fake_rmdir(path):
+            calls.append(path)
+            if len(calls) < 2:
+                raise OSError(errno.EBUSY, 'Device or resource busy', path)
+            os.unlink(self.partition)
+            real_rmdir(path)
+
+        with mock.patch('tuna.cpuset.os.rmdir', side_effect=fake_rmdir), \
+             mock.patch('tuna.cpuset.time.sleep'):
+            self.cs.destroy()
+        self.assertEqual(len(calls), 2)
+        self.assertFalse(os.path.exists(self.path))
+
+    def test_context_manager_uses_the_same_teardown(self):
+        """Leaving an auto_destroy block must demote, not just rmdir"""
+        Path(self.partition).write_text('isolated\n')
+        seen = {}
+        real_rmdir = os.rmdir
+        cs = fake_cpuset(self.path)
+        cs.auto_destroy = True
+
+        def fake_rmdir(path):
+            seen['partition'] = Path(self.partition).read_text()
+            os.unlink(self.partition)
+            real_rmdir(path)
+
+        with mock.patch('tuna.cpuset.os.rmdir', side_effect=fake_rmdir):
+            with cs:
+                pass
+        self.assertEqual(seen['partition'], 'member\n')
+        self.assertFalse(os.path.exists(self.path))
+
+    def test_destroy_missing_dir_is_a_noop(self):
+        cs = fake_cpuset(os.path.join(self.tmp.name, 'never-created'))
+        cs.destroy()
+
+    def test_destroy_without_partition_file(self):
+        real_rmdir = os.rmdir
+
+        def fake_rmdir(path):
+            real_rmdir(path)
+
+        with mock.patch('tuna.cpuset.os.rmdir', side_effect=fake_rmdir):
+            self.cs.destroy()
+        self.assertFalse(os.path.exists(self.path))
+
+
 @unittest.skipUnless(sys.platform.startswith('linux') and os.geteuid() == 0,
                      "Requires root permissions")
 @unittest.skipUnless(cpuset.CpusetsInit().supported, "Requires cgroup v2 support")
tuna/cpuset.py +50 -5

83 lines not on this page · raw message

Signature · 1 line
2.52.0