]> www.infradead.org Git - users/hch/misc.git/commitdiff
selftests: net: Add python context manager for netns entering
authorXiao Liang <shaw.leon@gmail.com>
Wed, 19 Feb 2025 12:50:38 +0000 (20:50 +0800)
committerJakub Kicinski <kuba@kernel.org>
Fri, 21 Feb 2025 23:28:03 +0000 (15:28 -0800)
Change netns of current thread and switch back on context exit.
For example:

    with NetNSEnter("ns1"):
        ip("link add dummy0 type dummy")

The command be executed in netns "ns1".

Signed-off-by: Xiao Liang <shaw.leon@gmail.com>
Link: https://patch.msgid.link/20250219125039.18024-13-shaw.leon@gmail.com
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
tools/testing/selftests/net/lib/py/__init__.py
tools/testing/selftests/net/lib/py/netns.py

index 7294578593165c0afa5f2844b0f2d84a6c25fbae..8697bd27dc305ce993b384e0682477855c24c36b 100644 (file)
@@ -2,7 +2,7 @@
 
 from .consts import KSRC
 from .ksft import *
-from .netns import NetNS
+from .netns import NetNS, NetNSEnter
 from .nsim import *
 from .utils import *
 from .ynl import NlError, YnlFamily, EthtoolFamily, NetdevFamily, RtnlFamily, RtnlAddrFamily
index ecff85f9074fd6cb63f1914b400278966b39a721..8e9317044eefebdcfdcc90eb811846cd76b5a232 100644 (file)
@@ -1,9 +1,12 @@
 # SPDX-License-Identifier: GPL-2.0
 
 from .utils import ip
+import ctypes
 import random
 import string
 
+libc = ctypes.cdll.LoadLibrary('libc.so.6')
+
 
 class NetNS:
     def __init__(self, name=None):
@@ -29,3 +32,18 @@ class NetNS:
 
     def __repr__(self):
         return f"NetNS({self.name})"
+
+
+class NetNSEnter:
+    def __init__(self, ns_name):
+        self.ns_path = f"/run/netns/{ns_name}"
+
+    def __enter__(self):
+        self.saved = open("/proc/thread-self/ns/net")
+        with open(self.ns_path) as ns_file:
+            libc.setns(ns_file.fileno(), 0)
+        return self
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        libc.setns(self.saved.fileno(), 0)
+        self.saved.close()