|
| 1 | +.. SPDX-License-Identifier: MPL-2.0 |
| 2 | +.. SPDX-FileCopyrightText: 2024 igo95862 |
| 3 | +
|
| 4 | +Tips and tricks |
| 5 | +=============== |
| 6 | + |
| 7 | +Using ProcessPoolExecutor to preserve current namespaces |
| 8 | +-------------------------------------------------------- |
| 9 | + |
| 10 | +When unsharing namespaces or switching to existing ones |
| 11 | +**there is no way to switch namespaces back**. The namespaces |
| 12 | +are process-wide so to preserve the current namespaces any |
| 13 | +concurrency methods that utilize independent processes can be used. |
| 14 | + |
| 15 | +For example, ``ProcessPoolExecutor`` from the standard library's |
| 16 | +`concurrent.futures <https://docs.python.org/3/library/concurrent.futures.html#processpoolexecutor>`_ |
| 17 | +module. |
| 18 | + |
| 19 | +Example:: |
| 20 | + |
| 21 | + from concurrent.futures import ProcessPoolExecutor |
| 22 | + |
| 23 | + from lxns.namespaces import UserNamespace |
| 24 | + |
| 25 | + |
| 26 | + def test() -> int: |
| 27 | + UserNamespace.unshare() |
| 28 | + return UserNamespace.get_current_ns_id() |
| 29 | + |
| 30 | + |
| 31 | + def main() -> None: |
| 32 | + print("My user NS id:", UserNamespace.get_current_ns_id()) |
| 33 | + |
| 34 | + with ProcessPoolExecutor() as executor: |
| 35 | + print("Subprocess user NS id:", executor.submit(test).result(1)) |
| 36 | + |
| 37 | + print("My user NS id after:", UserNamespace.get_current_ns_id()) |
| 38 | + |
| 39 | + |
| 40 | + if __name__ == "__main__": |
| 41 | + main() |
| 42 | + |
| 43 | + |
| 44 | +Executors can also be used with non-blocking asyncio:: |
| 45 | + |
| 46 | + from asyncio import get_running_loop |
| 47 | + from asyncio import run as asyncio_run |
| 48 | + from concurrent.futures import ProcessPoolExecutor |
| 49 | + |
| 50 | + from lxns.namespaces import UserNamespace |
| 51 | + |
| 52 | + |
| 53 | + def test() -> int: |
| 54 | + UserNamespace.unshare() |
| 55 | + return UserNamespace.get_current_ns_id() |
| 56 | + |
| 57 | + |
| 58 | + async def main() -> None: |
| 59 | + print("My user NS id:", UserNamespace.get_current_ns_id()) |
| 60 | + |
| 61 | + loop = get_running_loop() |
| 62 | + |
| 63 | + with ProcessPoolExecutor() as executor: |
| 64 | + fut = loop.run_in_executor(executor, test) |
| 65 | + print("Not blocked!") |
| 66 | + print("Subprocess user NS id:", await fut) |
| 67 | + |
| 68 | + print("My user NS id after:", UserNamespace.get_current_ns_id()) |
| 69 | + |
| 70 | + |
| 71 | + if __name__ == "__main__": |
| 72 | + asyncio_run(main()) |
| 73 | + |
| 74 | +The downside is that `only functions that can be pickled <https://python.readthedocs.io/en/stable/library/pickle.html#what-can-be-pickled-and-unpickled>`_ |
| 75 | +are supported. |
0 commit comments