[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <20241113125715.150201-6-shaw.leon@gmail.com>
Date: Wed, 13 Nov 2024 20:57:14 +0800
From: Xiao Liang <shaw.leon@...il.com>
To: netdev@...r.kernel.org,
linux-kselftest@...r.kernel.org,
Kuniyuki Iwashima <kuniyu@...zon.com>,
Jakub Kicinski <kuba@...nel.org>,
Donald Hunter <donald.hunter@...il.com>
Cc: "David S. Miller" <davem@...emloft.net>,
David Ahern <dsahern@...nel.org>,
Eric Dumazet <edumazet@...gle.com>,
Paolo Abeni <pabeni@...hat.com>,
Ido Schimmel <idosch@...dia.com>,
Andrew Lunn <andrew+netdev@...n.ch>,
Simon Horman <horms@...nel.org>,
Shuah Khan <shuah@...nel.org>,
Jiri Pirko <jiri@...nulli.us>,
Hangbin Liu <liuhangbin@...il.com>,
linux-rdma@...r.kernel.org,
linux-can@...r.kernel.org,
osmocom-net-gprs@...ts.osmocom.org,
bpf@...r.kernel.org,
linux-ppp@...r.kernel.org,
wireguard@...ts.zx2c4.com,
linux-wireless@...r.kernel.org,
b.a.t.m.a.n@...ts.open-mesh.org,
bridge@...ts.linux.dev,
linux-wpan@...r.kernel.org,
linux-kernel@...r.kernel.org
Subject: [PATCH net-next v3 5/6] selftests: net: Add python context manager for netns entering
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@...il.com>
---
tools/testing/selftests/net/lib/py/__init__.py | 2 +-
tools/testing/selftests/net/lib/py/netns.py | 18 ++++++++++++++++++
2 files changed, 19 insertions(+), 1 deletion(-)
diff --git a/tools/testing/selftests/net/lib/py/__init__.py b/tools/testing/selftests/net/lib/py/__init__.py
index 54d8f5eba810..e2d6c7b63019 100644
--- a/tools/testing/selftests/net/lib/py/__init__.py
+++ b/tools/testing/selftests/net/lib/py/__init__.py
@@ -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
diff --git a/tools/testing/selftests/net/lib/py/netns.py b/tools/testing/selftests/net/lib/py/netns.py
index ecff85f9074f..8e9317044eef 100644
--- a/tools/testing/selftests/net/lib/py/netns.py
+++ b/tools/testing/selftests/net/lib/py/netns.py
@@ -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()
--
2.47.0
Powered by blists - more mailing lists